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)

效果如图:

相关推荐
天天进步20151 小时前
【Nanobrowser源码分析4】交互篇: 从指令到动作:模拟点击、滚动与输入的底层实现
开发语言·javascript·ecmascript
console.log('npc')1 小时前
vue2中子组件父组件的修改参数
开发语言·前端·javascript
码点1 小时前
【无标题】日文字库Japan.ini
开发语言
IT=>小脑虎1 小时前
2026版 Python零基础小白学习知识点【基础版详解】
开发语言·python·学习
wjs20242 小时前
抽象工厂模式
开发语言
lly2024062 小时前
SVG 模糊效果详解
开发语言
期待のcode2 小时前
Java虚拟机类加载机制
java·开发语言
Learner2 小时前
Python运算符
开发语言·python
一晌小贪欢2 小时前
Python 精确计算:告别浮点数陷阱,decimal 模块实战指南
开发语言·python·python入门·python3·python小数·python浮点数
superman超哥2 小时前
Rust 范围模式(Range Patterns):边界检查的优雅表达
开发语言·后端·rust·编程语言·rust范围模式·range patterns·边界检查