swift UIAlertController用于弹出对话框消息,这里将介绍UIAlertController输入框案例的实现方法,使用比较简单,首先我们创建两个UIButton按钮,给button按钮添加点击事件,如图。
在ViewController.swift中实现这两个点击事件,代码如下。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
//弹出普通提示框
@IBAction func clickDelBtn(_ sender: UIButton) {
let alertController = UIAlertController.init(title: "提示", message: "数据删除成功", preferredStyle:.alert)
let cancel = UIAlertAction.init(title: "好的", style: UIAlertActionStyle.cancel) { (action:UIAlertAction) ->() in
print("处理完成\(action)")
}
alertController.addAction(cancel);
self.present(alertController, animated: true, completion: nil)
}
//弹出带有输入框的提示框
@IBAction func clickInputBtn(_ sender: UIButton) {
//初始化UITextField
var inputText:UITextField = UITextField();
let msgAlertCtr = UIAlertController.init(title: "提示", message: "请输入用户名", preferredStyle: .alert)
let ok = UIAlertAction.init(title: "确定", style:.default) { (action:UIAlertAction) ->() in
if((inputText.text) == ""){
print("你输入的是:\(String(describing: inputText.text))")
}
}
let cancel = UIAlertAction.init(title: "取消", style:.cancel) { (action:UIAlertAction) -> ()in
print("取消输入")
}
msgAlertCtr.addAction(ok)
msgAlertCtr.addAction(cancel)
//添加textField输入框
msgAlertCtr.addTextField { (textField) in
//设置传入的textField为初始化UITextField
inputText = textField
inputText.placeholder = "输入数据"
}
//设置到当前视图
self.present(msgAlertCtr, animated: true, completion: nil)
}
}
UIAlertController运行之后效果分别如图所示。
对着swift案例练习一遍吧!
网友评论