IOS-UIAlertController简单使用-Swift

UIAlertControlle时IOS的对话框控制器(警报控制器),简单使用方法如下:

步骤都一样,先是创建UIAlertController,然后创建UIAlertAction,再将UIAlertAction添加到UIAlertController中,最后显示对话框。

文本对话框:

swift 复制代码
		//创建控制器
        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
        //设置action
        let okAction = UIAlertAction(title: "OK", style: .default){
            (action) in
            print("click OK")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        //添加action
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        //显示对话框
        present(alertController, animated: true, completion: nil)

效果如图:

带输入框的对话框

swift 复制代码
		//创建控制器
        let alertController = UIAlertController(title: "Enter Text", message: nil, preferredStyle: .alert)
        //设置输入框
        alertController.addTextField { (textField) in
            textField.placeholder = "Enter text"
        }
        //设置action
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        let submitAction = UIAlertAction(title: "Submit", style: .default) { (action) in
            if let text = alertController.textFields?.first?.text {
                print("Entered text: \(text)")
            }
        }
        //添加action
        alertController.addAction(cancelAction)
        alertController.addAction(submitAction)
        //显示对话框
        present(alertController, animated: true, completion: nil)

效果如图:

底部选择对话框

注意preferredStyle为.actionSheet

swift 复制代码
		//创建控制器
        let alertController = UIAlertController(title: "Choose Option", message: nil, preferredStyle: .actionSheet)
        //设置action
        let option1Action = UIAlertAction(title: "Option 1", style: .default) { (action) in
            print("Option 1 selected")
        }
        let option2Action = UIAlertAction(title: "Option 2", style: .default) { (action) in
            print("Option 2 selected")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        //添加action
        alertController.addAction(option1Action)
        alertController.addAction(option2Action)
        alertController.addAction(cancelAction)
        //显示对话框
        present(alertController, animated: true, completion: nil)

效果如图:

相关推荐
梓䈑7 分钟前
【C语言】自定义类型:结构体
c语言·开发语言·windows
鱼跃鹰飞24 分钟前
Leecode热题100-295.数据流中的中位数
java·服务器·开发语言·前端·算法·leetcode·面试
小蜗笔记31 分钟前
在Python中实现多目标优化问题(7)模拟退火算法的调用
开发语言·python·模拟退火算法
杨荧37 分钟前
【JAVA开源】基于Vue和SpringBoot的水果购物网站
java·开发语言·vue.js·spring boot·spring cloud·开源
知识分享小能手1 小时前
mysql学习教程,从入门到精通,SQL 修改表(ALTER TABLE 语句)(29)
大数据·开发语言·数据库·sql·学习·mysql·数据分析
魏大橙1 小时前
Fastjson反序列化
开发语言·python
cyz1410011 小时前
vue3+vite@4+ts+elementplus创建项目详解
开发语言·后端·rust
立黄昏粥可温1 小时前
Python 从入门到实战34(实例2:绘制蟒蛇)
开发语言·python
ya888g1 小时前
蓝桥等级考试C++组17级真题-2023-05-21
开发语言·c++·蓝桥杯