swift - uilalertcontroller textfield值返回空

时间:2014-11-14 23:19:48

标签: ios swift textfield uialertcontroller

我一直盯着这几个小时,无法弄清楚我做错了什么。以下代码不断创建一个新的" Book"对象,但BookName为空...

这是我的代码:

var alert = UIAlertController(title: "New Book", message: "What is the name of this Book?", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
alert.addTextFieldWithConfigurationHandler { (textField) in
    textField.placeholder = "New Book Name"
    self.currentShelf.addNewBook(Book(bookName: textField.text))
}

self.presentViewController(alert, animated: true, completion: nil)

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

看起来你在addTextFieldWithConfigurationHandler方法中丢失了闭包的返回值,我相信你必须让自己成为文本域委托来接收输入。

确保类采用UITextFieldDelegate协议:

class MyViewController: UIViewController, UITextFieldDelegate, etc...

然后添加委托行并将缺少的Void返回添加到完成处理程序:

var alert = UIAlertController(title: "New Book", message: "What is the name of this Book?",  preferredStyle: UIAlertControllerStyle.Alert)
  alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
  alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in
    textField.delegate = self
    textField.placeholder = "New Book Name"
    self.currentShelf.addNewBook(Book(bookName: textField.text))
})

self.presentViewController(alert, animated: true, completion: nil)

我也强制将textField解包为UITextField!因为如果可以的话,我觉得它在Swift中总是最安全的。它稍微破坏了更清晰,装饰较少的Swift语法,但我发现它确保了更高的类型安全性。回顾过去几次我已经完成了这个,我还在return前面的})结束了没有返回值的关闭,但我认为这是原始Swift beta的遗留问题没有它就编好了。

希望这有帮助!