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)

效果如图:

相关推荐
小羊没烦恼!18 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读19 小时前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
C语言小火车20 小时前
C/C++ 为什么需要编译器?
开发语言·c++
霍霍的袁21 小时前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超21 小时前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int21 小时前
深入理解C++系列(20)——C++11(下)
开发语言·c++
CoderYanger1 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
茶底世界之下1 天前
为什么预览、录制、离线导出不能共享同一个背压策略?
ios·swift
2501_916007471 天前
苹果商店iOS应用上架费用全面解析:开发者计划与审核费用计算
android·ios·小程序·https·uni-app·iphone·webview
伞伞悦读1 天前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json