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)

效果如图:

相关推荐
过客猫20224 分钟前
使用 deepseek实现 go语言,读取文本文件的功能,要求支持 ascii,utf-8 等多种格式自适应
开发语言·后端·golang
程序媛-徐师姐15 分钟前
基于 Python Django 的校园互助平台(附源码,文档)
开发语言·python·django·校园互助·校园互助平台
进击的_鹏33 分钟前
【C++】list 链表的使用+模拟实现
开发语言·c++·链表
m0_7383556941 分钟前
java泛型
java·开发语言
大模型铲屎官1 小时前
哈希表入门到精通:从原理到 Python 实现全解析
开发语言·数据结构·python·算法·哈希算法·哈希表
L_09071 小时前
【C】队列与栈的相互转换
c语言·开发语言·数据结构
qq4054251971 小时前
基于python的旅客游记和轨迹分析可视化系统设计(新)
开发语言·python
C#Thread2 小时前
C#上位机--进程和线程的区别
java·开发语言
DKPT2 小时前
计算机网络之路由协议(自治系统)
开发语言·笔记·学习·计算机网络·算法
水月梦镜花2 小时前
数据结构:基数排序(c++实现)
开发语言·数据结构·c++