2014-11-14 45 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測試版的遺留問題,沒有它就編譯好。

希望這會有所幫助!