Cannot get text from UITextField - Swift - iOS

ぃ、小莉子 提交于 2019-12-23 02:31:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!