Swift - 告警提示框(UIAlertController)的用法

自 iOS8 起,苹果就建议告警框使用 UIAlertController 来代替 UIAlertView 和 UIActionSheel。

1,简单的应用(同时按钮响应Handler使用闭包函数)

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

    }

    override func viewDidAppear(_ animated: Bool){

        super.viewDidAppear(animated)

        let alertController = UIAlertController(title: "系统提示",

                        message: "您确定要开始学习吗?", preferredStyle: .alert)

        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)

        let okAction = UIAlertAction(title: "好的", style: .default, handler: {

            action in

            print("点击了确定")

        })

        alertController.addAction(cancelAction)

        alertController.addAction(okAction)

        self.present(alertController, animated: true, completion: nil)

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }

}

2,除了弹出,还可以使用从底部向上滑出的样式

(注意:如果上拉菜单中有“取消”按钮的话,那么它永远都会出现在菜单的底部,不管添加的次序是如何)

let alertController = UIAlertController(title: "保存或删除数据", message: "删除数据将不可恢复",

                                        preferredStyle: .actionSheet)

let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)

let deleteAction = UIAlertAction(title: "删除", style: .destructive, handler: nil)

let archiveAction = UIAlertAction(title: "保存", style: .default, handler: nil)

alertController.addAction(cancelAction)

alertController.addAction(deleteAction)

alertController.addAction(archiveAction)

self.present(alertController, animated: true, completion: nil)

3,按钮使用“告警”样式(文字颜色变红,用来来警示用户)

let okAction = UIAlertAction(title: "好的", style: .destructive, handler: nil)

4,添加任意数量文本输入框(比如可以用来实现个登陆框)

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

    }

    override func viewDidAppear(_ animated: Bool){

        super.viewDidAppear(animated)

        let alertController = UIAlertController(title: "系统登录",

                            message: "请输入用户名和密码", preferredStyle: .alert)

        alertController.addTextField {

            (textField: UITextField!) -> Void in

            textField.placeholder = "用户名"

        }

        alertController.addTextField {

            (textField: UITextField!) -> Void in

            textField.placeholder = "密码"

            textField.isSecureTextEntry = true

        }

        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)

        let okAction = UIAlertAction(title: "好的", style: .default, handler: {

            action in

            //也可以用下标的形式获取textField let login = alertController.textFields![0]

            let login = alertController.textFields!.first!

            let password = alertController.textFields!.last!

            print("用户名:\(login.text) 密码:\(password.text)")

        })

        alertController.addAction(cancelAction)

        alertController.addAction(okAction)

        self.present(alertController, animated: true, completion: nil)

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }

}

5,使用代码移除提示框

self.presentedViewController?.dismiss(animated: false, completion: nil)

6,提示框弹出后,过段时间自动移除

下面样例弹出一个不带按钮的消息提示框,过个两秒钟提示框自动消失。

let alertController = UIAlertController(title: "保存成功!",

                                        message: nil, preferredStyle: .alert)

//显示提示框

self.present(alertController, animated: true, completion: nil)

//两秒钟后自动消失

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {

    self.presentedViewController?.dismiss(animated: false, completion: nil)

}

附:扩展 UIAlertController 方便使用

从上面的样例可以发现,每次要弹出提示框都要创建一个 UIAlertController,然后添加 action 按钮,最后再通过对应的视图控制器 present 出来。我们可以对 UIAlertController 进行个扩展,把这些操作做个封装,方便使用。

1,UIAlertController扩展(UIAlertExtension.swift)

这里增加两种提示框效果:普通消息提示框、确认提示框。并且每个提示框都可以指定显示的 VC(不指定的话则为根 VC)

import UIKit

extension UIAlertController {

    //在指定视图控制器上弹出普通消息提示框

    static func showAlert(message: String, in viewController: UIViewController) {

        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "确定", style: .cancel))

        viewController.present(alert, animated: true)

    }

    //在根视图控制器上弹出普通消息提示框

    static func showAlert(message: String) {

        if let vc = UIApplication.shared.keyWindow?.rootViewController {

            showAlert(message: message, in: vc)

        }

    }

    //在指定视图控制器上弹出确认框

    static func showConfirm(message: String, in viewController: UIViewController,

                            confirm: ((UIAlertAction)->Void)?) {

        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "取消", style: .cancel))

        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: confirm))

        viewController.present(alert, animated: true)

    }

    //在根视图控制器上弹出确认框

    static func showConfirm(message: String, confirm: ((UIAlertAction)->Void)?) {

        if let vc = UIApplication.shared.keyWindow?.rootViewController {

            showConfirm(message: message, in: vc, confirm: confirm)

        }

    }

}

2,使用样例

下面分别调用两种提示框:

//弹出普通消息提示框

UIAlertController.showAlert(message: "保存成功!")

//弹出确认选择提示框

UIAlertController.showConfirm(message: "是否提交?") { (_) in

    print("点击了确认按钮!")

}


图片发自简书App
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容