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)

效果如图:

相关推荐
_x_w18 分钟前
【12】数据结构之基于线性表的排序算法
开发语言·数据结构·笔记·python·算法·链表·排序算法
不爱学英文的码字机器25 分钟前
Rust 的征服:从系统编程到全栈开发的 IT 新宠
开发语言·后端·rust
q567315232 小时前
用Dispatch库的爬虫程序爬取图片网站
开发语言·爬虫·python·scrapy
knightkkzboy2 小时前
《C语言中的“魔法盒子”:自定义函数的奇妙之旅》
c语言·开发语言·函数
Jelena技术达人2 小时前
深入解析:Python 爬取淘宝商品上下架接口
开发语言·python
菠萝崽.2 小时前
springboot中测试python脚本:ProcessBuilder
java·开发语言·spring boot·python·processbuilder
仙人掌_lz2 小时前
详解如何从零用 Python复现类似 GPT-4o 的多模态模型
开发语言·python·gpt·llm·gpt-4o·deepseek
努力学习的小廉2 小时前
【智能指针】—— 我与C++的不解之缘(三十三)
开发语言·c++
AAA码农烧烤2 小时前
神经网络入门—井字棋游戏
开发语言·python·游戏
Java小白中的菜鸟3 小时前
深入理解Java反射
java·开发语言