跟着斯坦福白胡子老头学Alert

跟着斯坦福白胡子老头学Alert_第1张图片
alert样式

iOS使用UIAlertController类实现基本的对话框、单选菜单功能,可以显示标题、内容、选项、按钮、输入框等控件; alert分为2种类型即actionSheet和alert, 分别对应菜单和对话框样式。


public enum UIAlertControllerStyle : Int {
case actionSheet
case alert
}

显示在界面底部的菜单(或者iPad下拉菜单):

 let alert = UIAlertController(title: "测试标题",
message: "测试内容",
preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "是",
style: .default, //按钮样式
handler: { (action: UIAlertAction) in
print("点击 是 ")
}
))

    alert.addAction(UIAlertAction(title: "否",  
                                  style: .destructive,  
                                  handler: { (action: UIAlertAction) in  
                                    print("点击  否")  
    }))  
      
    alert.addAction(UIAlertAction(title: "Cancel",  
                                  style: .cancel,  //按钮样式  
        handler: { (action: UIAlertAction) in  
            print("点击 Cancel")  
    }))  
      
      
    //在iPad上有效,显示下拉菜单; 在iPhone上ppc为nil, 总是显示actionSheet样式  
    alert.modalPresentationStyle = .popover  
    let ppc = alert.popoverPresentationController   //在iPhone上ppc为nil,iPad上有值  
    ppc?.barButtonItem = menuBarItem  
      
    present(alert, animated: true, completion: {  
        print("显示完成")  
    })  

如果要显示对话框, 只有修改preferredStyle为.alert就可以了。

 let alert = UIAlertController(title: "测试标题",
message: "测试内容",
preferredStyle: .alert)
......

UIAlertController只支持显示一个输入框。

 ...
alert.addAction(UIAlertAction(
title: "login",
style: .default,
handler: {(action: UIAlertAction) in
//取出输入框的值做逻辑
print(alert.textFields?.first?.text ?? "there is nothing") //输入框的值

}))
//设置输入框的默认值
alert.addTextField(configurationHandler: {(textField) in
textField.placeholder = "please input name" //默认值
})
...

注意: 闭包运行在进程的主DispatchQueue里, 不要做耗时操作!

你可能感兴趣的:(跟着斯坦福白胡子老头学Alert)