Swift_ios_UIAlertController之text
2016-01-07 本文已影响908人
ChinaSwift
- 'UIAlertView'在iOS 9.0已经废除,所以我们将以前对它的使用转移到:UIAlertController上来。
- UIAlertController完全能够胜任UIAlertView所需的功能
- UIAlertController 类不仅用于呈现警告弹窗,还能够提供 Text Fields 来获取文本信息输入。
- 关于UIAlertController里如果添加了UITextField的话,在UIAlertController消失之后怎么获取UITextField的值,应该有以下几种方法。
1.UIAlertController的代理函数实现
2.设置监听器传值
3.设置中间变量传值(个人觉得最简洁,最容易理解)
- 下面将直接奉上N.O.3<设置中间变量传值方式>的代码
@IBAction func download(sender: AnyObject) {
var textF1 = UITextField() //设置中间变量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)
}
- 介绍完<设置中间变量传值方式>,再来介绍<设置监听器传值>方式
@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消失时移除监听器
NSNotificationCenter.defaultCenter().removeObserver(self)
}
alertC.addTextFieldWithConfigurationHandler { (textField1) -> Void in
textF1 = textField1
textF1.placeholder = "hello grandre"
//第一步 在UIAlertController添加UITextField时添加监听器
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)
}
//第二步 在控制器中添加监听到事件后的执行方法
func handleFuntion(notification: NSNotification) {
let textFied = notification.object as! UITextField
print("-----\(textFied.text)")
}