[英]How can I reference the text of a UITextField in Swift?
我試圖引用UITextField
的文本,以便可以在應用程序的不同位置使用它。
@IBOutlet weak var mealNameUITextField: UITextField!
@IBAction func nextButton(sender: AnyObject) {
mealNameBeingCreated = String(mealNameUITextField.text)
print(mealNameBeingCreated)
}
這給了我錯誤:
致命錯誤:解開Optional值時意外發現nil
誰能告訴我引用文本的正確方法? 另外,最好提及我要在全局變量中使用此信息。
像這樣寫:
@IBAction func nextButton(sender: AnyObject) {
let mealNameBeingCreated : String = mealNameUITextField.text!
print(mealNameBeingCreated)
}
@IBAction func nextButton(sender: AnyObject) {
let mealNameBeingCreated:String = self.mealNameUITextfield.text!
print(mealNameBeingCreated)
}
要么
@IBAction func nextButton(sender: AnyObject) {
let mealNameBeingCreated = self.mealNameUITextfield.text!
print(mealNameBeingCreated)
}
文本字段返回的值是可選的,我們必須使用“!”將其解包。 符號
語法取決於您正在使用的Swift語言的版本。 我正在使用支持Swift 2.1.1的XCode 7.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.