【问题标题】:How to save text in TextField via Button click to a variable? [closed]如何通过按钮单击将 TextField 中的文本保存到变量? [关闭]
【发布时间】:2015-01-12 18:45:54
【问题描述】:

如何通过单击“保存”按钮将书面文本简单地保存到 Swift 中的变量“a”中?

我试过了

class YourViewController: UIViewController {
    @IBOutlet weak var textField: UITextField! //or UITextView


    //lifecycle methods and so on ...    

    @IBAction func saveTextToVar(sender: UIButton) {
        var text: NSString ?= textField.text
    }
}

但在测试我的应用时,我总是遇到错误。 http://www.bilder-upload.eu/upload/584458-1421163318.png

【问题讨论】:

  • 请用一些信息(研究或代码)更新您的问题。尝试一些事情。提供有关您遇到的问题的详细信息。

标签: ios button swift uitextfield


【解决方案1】:

您需要定义 IBOutlet,然后将其与您的 xib 或故事板连接。 在您需要定义动作并将“Touch up inside”按钮动作与您定义的动作联系起来之后。

这里是代码

class YourViewController: UIViewController {
    @IBOutlet weak var textField: UITextField! //or UITextView


    //lifecycle methods and so on ...    

    @IBAction func saveTextToVar(sender: UIButton) {
        var text: NSString ?= textField.text
    }
}

【讨论】:

  • BTW Swift 是一种类型推断语言。您应该始终使用 String 而不是 NSString 但只需省略类型即可。
  • 编译时错误:在接受答案的最后一行,一元运算符不能与其操作数分开。试试这个 -> var text = textField.text; println("文本值 = " + 文本);如果我错了,请纠正我。
猜你喜欢
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-22
  • 2017-02-09
相关资源
最近更新 更多