iOS8中的UIAlertView和UIActionSheet已經(jīng)都被UIAlertViewController代替了,所以,本篇blog就來探討下如何用swift生成提示框,
Swift完成UIAlertController的調(diào)用
。我們先來看一下Apple的UIAlertController的文檔:
import Foundationimport UIKit//// UIAlertController.h// UIKit//// Copyright (c) 2014 Apple Inc. All rights reserved.//@availability(iOS, introduced=8.0)enum UIAlertActionStyle. Int { case Default case Cancel case Destructive}@availability(iOS, introduced=8.0)enum UIAlertControllerStyle. Int { case ActionSheet case Alert}@availability(iOS, introduced=8.0)class UIAlertAction : NSObject, NSCopying { convenience init(title: String, style. UIAlertActionStyle, handler: ((UIAlertAction!) ->Void)!) var title: String { get } var style. UIAlertActionStyle. { get } var enabled: Bool}@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 }}
我們可以看到UIAlertController的style有兩個,一個是ActionSheet,一個是Alert,而AlertActionStyle有3個: Default,Cancel, Destructive;所以我們新建Alert時可以這樣:
var alert: UIAlertController = UIAlertController(title:nil, message:"您輸入的電話號碼有誤,請檢查后重新輸入", preferredStyle.:UIAlertControllerStyle.Alert)
或者
var alert: UIAlertController = UIAlertController(title: nil, message:"test", preferredStyle. UIAlertControllerStyle.ActionSheet)接下來我們來給Alert添加action,從文檔中可以看到AlertAction有init函數(shù),
我們來新建3個actions
var saveAction = UIAlertAction(title: "Save", style. .Default, handler:{ (alerts: UIAlertAction!) ->Void in println("File saved") }) var deleteAction = UIAlertAction(title: "Delete", style. .Default, handler:{ (alerts: UIAlertAction!) ->Void in println("File delete") }) var cancelAction = UIAlertAction(title: "Cancel", style. .Cancel, handler:{ (alerts: UIAlertAction!) ->Void in println("Cancelled") })注意到handler中用到了一個closure
然后給我們的alertcontroller添加actions,并把它顯示出來
alert.addAction(saveAction) alert.addAction(deleteAction) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil)
我們也可以這樣添加action
alert.addAction(UIAlertAction(title: "確定", style. .Destructive, handler: { action in switch action.style{ case .Default: println("ok") case .Cancel: println("cancel") case .Destructive: println("Destructive") } } ))接下來運行一下看看我們的alertController是什么樣子的吧,
電腦資料
《Swift完成UIAlertController的調(diào)用》(http://m.dameics.com)。Tips:
如果style是cancel 那么字體會變粗;如果是destructive,字體會顯示紅色。