swift - UIAlertController 的用法

ios 8 以后苹果官方建议使用UIAlertController这个类,所以专门去网上找资料,了解了下用法,

1、创建一个alertController


let alertController = UIAlertController(title: "系统提示",
            message: "您确定要离开吗?", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "好的", style: .default,
            handler: {
                action in
                print("点击了确定")
        })
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: {
    
        //这里可以做一些其他操作
    })

2、创建一个actionSheet

(注:如果上拉菜单中有“取消”按钮的话,那么它永远都会出现在菜单的底部,不管添加的次序是如何)

let alertController = UIAlertController(title: "保存或删除数据", message: "删除数据将不可恢复",
    preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let deleteAction = UIAlertAction(title: "删除", style: .destructive, handler: nil)
let archiveAction = UIAlertAction(title: "保存", style: .default, handler: nil)
alertController.addAction(cancelAction)
alertController.addAction(deleteAction)
alertController.addAction(archiveAction)
self.present(alertController, animated: true, completion: nil)

3、按钮使用警告模式,文字颜色变化,用来警示用户

var okAction = UIAlertAction(title: "好的", style: .destructive, handler: nil)

4、添加任意数量的文本输入框

 let myAlertController = UIAlertController(title:"系统登录",message:"请输入用户名和密码",preferredStyle:.alert)
        myAlertController.addTextField { (textField:UITextField) in
            textField.placeholder = "用户名"
        }
        
        myAlertController.addTextField { (textField:UITextField) in
            textField.placeholder = "密码"
            textField.isSecureTextEntry = true
        }
        
        myAlertController.addTextField { (textField:UITextField) in
            textField.placeholder = "重复密码"
            textField.isSecureTextEntry = true
        }
        
        let cancelAction = UIAlertAction(title:"取消",style:.cancel,handler:nil)
        let okAction = UIAlertAction(title:"确定",style:.default,
               handler:{
                action in
                let login = myAlertController.textFields?.first
                let passWord = myAlertController.textFields?.last
                print("用户名是:\(String(describing: login)) 密码是:\(String(describing: passWord))")
        })
        
        myAlertController.addAction(cancelAction)
        myAlertController.addAction(okAction)
        self.present(myAlertController, animated: true) {
            self.view.backgroundColor = UIColor.blue
        }

 

如图

 

 5、使用代码移除提示框

 

self.dismiss(animated: true) { 
          //其他操作  
}

 

posted @ 2016-07-22 13:33  稻草人11223  阅读(360)  评论(0编辑  收藏  举报
返回顶部