问题
I have an iOS app written in Swift. I am struggling to get the text from the UITextField because my app crashes on this line of code:
let dataUser = self.userField.text
I get the following crash report:
fatal error: unexpectedly found nil while unwrapping an Optional value
What am I doing wrong?... all I want to do is get the text from the text field.
Thanks, Dan.
回答1:
Check in Interface Builder that your UITextField is properly linked to your "userField" IBOutlet: your UITextField, self.userField
, is probably not hooked to the IBOutlet, so the object is nil and it crashes when trying to access its .text
property.
回答2:
In swift 2.0 the text value of UITextField became optional.
So check if exists first:
guard let text = self.userField.text else {
print("ooops")
return
}
let dataUser = text
来源:https://stackoverflow.com/questions/33129347/cannot-get-text-from-uitextfield-swift-ios