swift中UIAlertView的使用

来源:互联网 发布:考研院校专业数据库 编辑:程序博客网 时间:2024/04/29 03:08
[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // 方法1  
  2. let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: alertCancel)  
  3. alertView.show()  
[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // 方法2  
  2. // 实例化时添加代理对象(注意添加协议)  
  3. let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegateself, cancelButtonTitle: alertCancel, otherButtonTitles: alertOK, "提示""通告""警告")  
  4. alertView.show()  
[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // 添加协议 UIAlertViewDelegate  
  2. class ViewController: UIViewController, UIAlertViewDelegate {  
  3.       
  4.     override func viewDidLoad() {  
  5.     ...  
  6.    }  
  7.    ...  
  8. }  
[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // 实现协议方法  
  2. // MARK: UIAlertViewDelegate  
  3. func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {  
  4.         let buttonTitle = alertView.buttonTitleAtIndex(buttonIndex)  
  5.         if buttonTitle == alertCancel  
  6.         {  
  7.             print("你点击了取消")  
  8.         }  
  9.         else if buttonTitle == alertOK  
  10.         {  
  11.             print("你点击了确定")  
  12.         }  
  13.         else  
  14.         {  
  15.             print("你点击了其他")  
  16.         }  
  17. }  
[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // 方法3  
  2. // 1 实例化  
  3. let alertVC = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert)  
  4. // 2 带输入框  
  5. alertVC.addTextFieldWithConfigurationHandler {  
  6.             (textField: UITextField!) -> Void in  
  7.             textField.placeholder = "用户名"  
  8. }  
  9. alertVC.addTextFieldWithConfigurationHandler {  
  10.             (textField: UITextField!) -> Void in  
  11.             textField.placeholder = "密码"  
  12.             textField.secureTextEntry = true  
  13. }  
  14. // 3 命令(样式:退出Cancel,警告Destructive-按钮标题为红色,默认Default)  
  15. let alertActionCancel = UIAlertAction(title: alertCancel, style: UIAlertActionStyle.Destructive, handler: nil)  
  16. let alertActionOK = UIAlertAction(title: alertOK, style: UIAlertActionStyle.Default, handler: {  
  17.             action in  
  18.             print("OK")  
  19.               
  20.             // 3-1 获取输入框的输入信息  
  21.             let username = alertVC.textFields!.first! as UITextField  
  22.             let password = alertVC.textFields!.last! as UITextField  
  23.             print("用户名:\(username.text),密码:\(password.text)")  
  24. })  
  25. alertVC.addAction(alertActionCancel)  
  26. alertVC.addAction(alertActionOK)  
  27. // 4 跳转显示  
  28. self.presentViewController(alertVC, animatedtrue, completion: nil)  

方法1示例图


方法2示例图


方法3示例图



0 0