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)

效果如图:

相关推荐
郝学胜-神的一滴15 分钟前
建造者模式:构建复杂对象的优雅方式
开发语言·c++·程序人生·建造者模式
AAIshangyanxiu20 分钟前
最新基于R语言结构方程模型分析与实践技术应用
开发语言·r语言·结构方程模型·生态统计学
Fly-ping2 小时前
【前端】JavaScript 的事件循环 (Event Loop)
开发语言·前端·javascript
songgeb2 小时前
Concurrency in Swift学习笔记-初识
ios·swift
范纹杉想快点毕业2 小时前
基于C语言的Zynq SOC FPGA嵌入式裸机设计和开发教程
c语言·开发语言·数据库·嵌入式硬件·qt·fpga开发·嵌入式实时数据库
rockmelodies2 小时前
【PHP安全】免费解密支持:zend52、zend53、zend54好工具
开发语言·安全·php
Reggie_L2 小时前
Stream流-Java
java·开发语言·windows
巴伦是只猫3 小时前
Java 高频算法
java·开发语言·算法
程序员编程指南3 小时前
Qt容器类:QList、QMap等的高效使用
c语言·开发语言·c++·qt
雄狮少年3 小时前
智能体服务封装
开发语言·windows·python