UIAlertControlle时IOS的对话框控制器(警报控制器),简单使用方法如下:
步骤都一样,先是创建UIAlertController,然后创建UIAlertAction,再将UIAlertAction添加到UIAlertController中,最后显示对话框。
文本对话框:
//创建控制器let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)//设置actionlet okAction = UIAlertAction(title: "OK", style: .default){(action) inprint("click OK")}let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)//添加actionalertController.addAction(okAction)alertController.addAction(cancelAction)//显示对话框present(alertController, animated: true, completion: nil)
效果如图:
带输入框的对话框
//创建控制器let alertController = UIAlertController(title: "Enter Text", message: nil, preferredStyle: .alert)//设置输入框alertController.addTextField { (textField) intextField.placeholder = "Enter text"}//设置actionlet cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)let submitAction = UIAlertAction(title: "Submit", style: .default) { (action) inif let text = alertController.textFields?.first?.text {print("Entered text: \(text)")}}//添加actionalertController.addAction(cancelAction)alertController.addAction(submitAction)//显示对话框present(alertController, animated: true, completion: nil)
效果如图:
底部选择对话框
注意preferredStyle为.actionSheet
//创建控制器let alertController = UIAlertController(title: "Choose Option", message: nil, preferredStyle: .actionSheet)//设置actionlet option1Action = UIAlertAction(title: "Option 1", style: .default) { (action) inprint("Option 1 selected")}let option2Action = UIAlertAction(title: "Option 2", style: .default) { (action) inprint("Option 2 selected")}let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)//添加actionalertController.addAction(option1Action)alertController.addAction(option2Action)alertController.addAction(cancelAction)//显示对话框present(alertController, animated: true, completion: nil)
效果如图: