[英]swift - uilalertcontroller textfield value returning empty
我一直盯着這個看了好幾個小時,無法弄清楚我在做什么錯。 以下代碼繼續創建新的“ Book”對象,但BookName為Blank ...
這是我的代碼:
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)
謝謝你的幫助
看來您丟失了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
前上線})
沒有返回值,但我認為這是原來斯威夫特公測的遺產,它沒有它編譯罰款。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.