2014-11-14 46 views
0

我一直盯着这几个小时,无法弄清楚我做错了什么。下面的代码保存创建一个新的“书”的对象,但BOOKNAME是空白......swift - uilalertcontroller textfield value returns empty

这里是我的代码:

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) 

感谢您的帮助

回答

0

它看起来像你失去了从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) 

我也力解开文本字段作为的UITextField!因为我觉得如果可以的话,在Swift中总是最安全的。它破坏了更简洁,装饰较少的Swift语法,但我发现它确保了更高的类型安全性。回顾一下这段时间我已经完成了这个工作,我也在})之前结束了return的关闭,但没有返回值,但我认为这是原始Swift测试版的遗留问题,没有它就编译好。

希望这会有所帮助!