iOS8之后苹果添加了 UIAlertContoller 来替代 UIAlertView与UIActionSheet
我们首先介绍在 swift 中怎么使用 UIAlertController
UIAlertController 初始化 let alertController: UIAlertController = UIAlertController (title: “ 我是 标题君 " , message: " 要优雅 " , preferredStyle: . Alert ) 最后设置弹框类型的参数 有两个值 . ActionSheet 底部框 . Alert 警告框 ps:两种类型弹框用法相同
初始化标签动作 let alertAction:UIAlertAction = UIAlertAction(title: "买买买", style: .Default, handler: { (action:UIAlertAction) -> Void in print ( “钱包生命值-999 " ) }) alertController . addAction (alertAction) 参数style设置标签风格有三种(级别) .Default 默认 .Cancel 取消 .Destructive 警示(红色字体) let alertAction2 : UIAlertAction = UIAlertAction (title: “我选择死亡 " , style: . Cancel , handler: { (action: UIAlertAction ) -> Void in print ( "我不会就这样轻易的狗带 " ) }) alertController . addAction ( alertAction2 ) let alertAction3 : UIAlertAction = UIAlertAction (title: 崩!啥卡拉卡! " , style: . Destructive , handler: { (action: UIAlertAction ) -> Void in print ( “恭喜玩家,你妈炸了 " ) }) alertController . addAction ( alertAction3 ) 模态推出视图 self.presentViewController( alertController , animated: true, completion: { () -> Void in print ( " 就是弹个框,别害怕,我不是什么好人 " ) }) 按钮如果达到3个或三个以上,会成一列显示。如果少于3个,则成一排显示。
那么问题来了,如何添加文字输入框呢(虽然我完全没在实践中用到过) alert. addTextFieldWithConfigurationHandler ({ (textField: UITextField ) -> Void in textField. placeholder = “我是帐号君 " }) alert.addTextFieldWithConfigurationHandler ({ ( textField: UITextField ) -> Void in textField. placeholder = “我是密码君 " textField. secureTextEntry = true // 密码模式 })
由于很多公司还兼容低版本(例如我们公司,之前兼容到 ios6.最近改为兼容到 ios7)所以 alertView 与 alertController 并用在所难免,github 上有封装的比较好的库,可以省去我们重复写大量代码的问题,swift不知道有没有,不过已经在 swift 的公司,应该不会兼容到低版本了,所以讲道理大概不存在此问题。
老旧的 UIAlertView 与 OC 一样,先初始化 uialertViewDelegate let alertView = UIAlertView (title: <#T##String#>, message: <#T##String#>, delegate: <#T##UIAlertViewDelegate?#>, cancelButtonTitle: <#T##String?#>, otherButtonTitles: <#T##String#>, <#T##moreButtonTitles: String...##String#>) alertView.show() 实现代理方法 func alertView(alertView: UIAlertView , didDismissWithButtonIndex buttonIndex: Int ) { }
UIActionSheet也与 OC 相同。