Swift UI专项训练35 UIAlertController

之前我们介绍过AlertView和ActionSheet的用法,前者显示页面中,而后者是从页面底部飞入的。IOS8中有个新的用法UIAlertController,用它就可以同时实现AlertView和ActionSheet,代码变得简便了很多。下面我们command进UIAlertController中看一下它的用法

@availability(iOS,introduced=8.0)
class UIAlertController : UIViewController {
    
    convenience init(title: String?,message: String?,preferredStyle: UIAlertControllerStyle)
    
    func addAction(action: UIAlertAction)
    var actions: [AnyObject] { get }
    func addTextFieldWithConfigurationHandler(configurationHandler: ((UITextField!) -> Void)!)
    var textFields: [AnyObject]? { get }
    
    var title: String?
    var message: String?
    
    var preferredStyle: UIAlertControllerStyle { get }
}

它的构造函数中有一个参数,preferredStyle,用来选择我们要实现的类型:
enum UIAlertControllerStyle : Int {
    
    case ActionSheet
    case Alert
}

UIAlertController只有这两个选择。下面我们分别来尝试一下,首先创建一个UIAlertController,选择ActionSheet类型:
var alertController = UIAlertController(title: "选择摇摇",message: nil,preferredStyle: .ActionSheet)//新写法
        var priceAction = UIAlertAction(title: "价格",style: .Default,handler: nil)
        alertController.addAction(priceAction)
        var scoreAction = UIAlertAction(title: "评分",handler: nil)
        alertController.addAction(scoreAction)
        self.presentViewController(alertController,animated: true,completion: nil)


运行一下:


可以看到它依然在屏幕的底部弹出,现在我们保持代码不变,只把.ActionSheet换成.Alert,来看看效果


怎么样,相比之前新建两个控制器,现在的用法是不是简单了很多?

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...