问题
So I'm trying to get the text of an input field in Swift. So here's what I got
class ViewController: UIViewController {
@IBOutlet var passwordField: UITextField!
@IBOutlet var usernameField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//Try to log user in by default
let user = usernameField.text
let password = passwordField.text
It all looks good (I know I didn't close the class, I just pulled it directly out) and when I go to run it, I get
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
and
(You'll have to open the image in a new tab to see it)
I binded the input fields with the IBOutlet successful, I know that. Any ideas?
回答1:
Try this way I think this will work :
if let abc = usernameField.text{
let user = abc
}
回答2:
i think You Have to Check This in TextField's Delegate Method
func textFieldDidEndEditing(textField: UITextField) {
}
instead ViewDidLoad Or On Action of ButtonClick
Cause TextField Are Empty On ViewDidLoad!
回答3:
I had this problem while setting the delegate to a text field. Couldn't figure out was wrong then realized that I had declared the class for a second view controller as a view controller not a UIViewController. I'm new at this.
来源:https://stackoverflow.com/questions/26701993/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-value-in-swift