- 'UIAlertView'在iOS 9.0已經(jīng)廢除,所以我們將以前對(duì)它的使用轉(zhuǎn)移到:UIAlertController上來。
- UIAlertController完全能夠勝任UIAlertView所需的功能
- UIAlertController 類不僅用于呈現(xiàn)警告彈窗,還能夠提供 Text Fields 來獲取文本信息輸入。
- 關(guān)于UIAlertController里如果添加了UITextField的話,在UIAlertController消失之后怎么獲取UITextField的值,應(yīng)該有以下幾種方法。
1.UIAlertController的代理函數(shù)實(shí)現(xiàn)
2.設(shè)置監(jiān)聽器傳值
3.設(shè)置中間變量傳值(個(gè)人覺得最簡潔,最容易理解)
- 下面將直接奉上N.O.3<設(shè)置中間變量傳值方式>的代碼
@IBAction func download(sender: AnyObject) {
var textF1 = UITextField() //設(shè)置中間變量textF1
let alertC = UIAlertController(title: "Alert Title", message: "Subtitle", preferredStyle: UIAlertControllerStyle.Alert)
let alertA = UIAlertAction(title: "1", style: UIAlertActionStyle.Default) { (act) -> Void in
print(textF1.text)
}
alertC.addTextFieldWithConfigurationHandler { (textField1) -> Void in
textF1 = textField1
textF1.placeholder = "hello grandre"
}
alertC.addAction(alertA)
self.showViewController(alertC, sender: nil)
}
- 介紹完<設(shè)置中間變量傳值方式>,再來介紹<設(shè)置監(jiān)聽器傳值>方式
@IBAction func download(sender: AnyObject) {
let alertC = UIAlertController(title: "Alert Title", message: "Subtitle", preferredStyle: UIAlertControllerStyle.Alert)
let alertA = UIAlertAction(title: "1", style: UIAlertActionStyle.Default) { (act) -> Void in
//第三步 在UIAlertController消失時(shí)移除監(jiān)聽器
NSNotificationCenter.defaultCenter().removeObserver(self)
}
alertC.addTextFieldWithConfigurationHandler { (textField1) -> Void in
textF1 = textField1
textF1.placeholder = "hello grandre"
//第一步 在UIAlertController添加UITextField時(shí)添加監(jiān)聽器
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleFuntion:", name: UITextFieldTextDidChangeNotification, object: textField1)
}
alertC.addAction(alertA)
// self.showViewController(alertC, sender: nil)
self.presentViewController(alertC, animated: true, completion: nil)
}
//第二步 在控制器中添加監(jiān)聽到事件后的執(zhí)行方法
func handleFuntion(notification: NSNotification) {
let textFied = notification.object as! UITextField
print("-----\(textFied.text)")
}