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

本文介绍如何使用 iOS 中的 UIAlertController 类创建对话框与菜单。通过设置样式可以实现不同类型的交互界面,如 actionSheet 和 alert,并展示了如何添加按钮及处理点击事件。此外还介绍了如何在 UIAlertController 中集成输入框。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                                                                   

  

        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里, 不要做耗时操作!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值