UIAlertView 和 UIAlertController

作者: 程序媛coco | 来源:发表于2015-06-25 18:41 被阅读7468次

UIAlertView 你应该对它都是再熟悉不过的了,但是在iOS8 里已经过期了,用来取代它的是UIAlertController-展示action sheet和modal alert。下面用swift带着你从UIAlertView转变到UIAlertController

一、 创建一个新项目
启动Xcode6.3+,创建一个基于Single View Application template的项目

QQ20150625-1.png

项目名AlertDemo, 设置语言为Swift,设置Devices为iPhone,Next 选择项目的存放地址,最后Create

QQ20150625-2.png

打开Main.stroyboard, 添加一个Button,设置好居中约束(其实不设也没有什么影响,只是可能位置会和预期的有偏差),用来点击显示Alert

QQ20150625-3.png

打开ViewController.swift,给stroyboard的Button拖线,添加 Touch Up Inside事件

@IBAction func showAlert(sender: AnyObject) {

}

二、 UIAlertView

初始化 UIAlertView, 调用show()

    @IBAction func showAlert(sender: AnyObject) {
        let alertView = UIAlertView(title: "Hi UIAlertView", message: "are you okay?", delegate: self, cancelButtonTitle: "no", otherButtonTitles: "yes")
        alertView.tag = 1
        alertView.show()
    }

设置 UIAlertView的代理 UIAlertViewDelegate

     import UIKit
     class ViewController: UIViewController, UIAlertViewDelegate {
       ...
     }

实现代理方法

    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
    if alertView.tag == 1 {
        if buttonIndex == 0 {
            println(" ok")
        } else {
            println(" not okay")
        }
    }
QQ20150625-4.png

三、UIAlertController

lalala.......重头戏来了, UIAlertController的接口和 UIAlertView非常不一样, 不需要使用代理协议,这样我们只需要在 button的 action方法里面实现即可

@IBAction func showAlert(sender: AnyObject) {
    //初始化 Alert Controller
    let alertController = UIAlertController(title: "Hi alertController!", message: "are you okay", preferredStyle: .Alert)
    
    //设置 Actions
    let yesAction = UIAlertAction(title: "yes", style: .Default){ (action) -> Void in
        println("ok!")
    }
    let noAction = UIAlertAction(title: "no", style: .Default){ (action) -> Void in
        println("no!")
    }
    
    //添加 Actions,添加的先后和显示的先后顺序是有关系的
    alertController.addAction(yesAction)
    alertController.addAction(noAction)
    
    //展示Alert Controller
    self.presentViewController(alertController, animated: true, completion: nil)
}

初始化方法很简单,只要设置title,message还有preferredStyle(UIAlertControllerStyle.Alert或者缩写.Alert;这个preferredStyle属性是告诉系统当前要展示的是一个Action Sheet .ActionSheet或者modal alert .Alert)

QQ20150625-5.png

总结

虽然UIAlertViewUIActionSheet在iOS8已经过期了,你仍然可以继续使用。UIAlertController这个接口类是一个定义上的提升,它添加简单,展示Alert和ActionSheet使用统一的API。因为UIAlertController使UIViewController的子类,他的API使用起来也会比较熟悉!没有骗你吧,很简单的东西,你用一遍就会了的,一起加油~

相关文章

网友评论

  • 天堂秀:很好,把我的问题解决了
  • 越天高:有个不地方不会用 以前 我在appaplagete里面在注册的alertView 希望在任何视图我都能显示。但是现在是alertViewController了就只能在一个rootViewController里显示 请问这个问题怎么解决 主要我是因为有推送的话判断程序的运行状态 如果实在运行的话 就显示出一个alertView
  • 07b26415786b:感谢 学习中 发现iOS已经更迭了很多 遇到debug时搞不懂的问题 来你家做客就知道如何解答了 多谢

本文标题:UIAlertView 和 UIAlertController

本文链接:https://www.haomeiwen.com/subject/oyleqttx.html