Apple 將 Alert Window 視為 ViewController, 而不是一個 View 的概念,所以以此取代 UIActionSheet 與 UIAlertView 類別。市面上若有 Swift 的書,Alert Dialog 的製作仍沿用 UIAlertView 為早期用法。 製作 Alert Dialog 的步驟如下: 1. 建立 Alert Dialog 物件 : UIAlertController 2. 建立 Alert Action 物件 : UIAlertAction 3. 將新建的 Alert Action 物件加入 Alert Dialog 物件清單 : UIAlertController.addAction 4. 顯示 Alert Dialog 物件 : UIViewController.presentViewController 以下依此步驟及Apple 的官方文件,逐步說明如何製作 Alert Dialog:1. Declaration: UIAlertController SWIFT convenience init(title title: String?, message message: String?, preferredStyle preferredStyle: UIAlertControllerStyle)
寫成: let alertController = UIAlertController(title : "My First App", message : "Hello,World!", preferredStyle : UIAlertControllerStyle.Alert)2.Declaration: UIAlertAction SWIFT convenience init(title title: String?, style style: UIAlertActionStyle, handler handler: ((UIAlertAction) -> Void)?)
寫成: let alertAction = UIAlertAction(title : "OK", style : UIAlertActionStyle.Default, handler : nil )3. Declaration: UIAlertController.addAction SWIFT func addAction(_ action: UIAlertAction)
寫成: alertController.addAction(alertAction)4. Declaration: UIViewController.presentViewController func presentViewController(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion completion: (() -> Void)?)
寫成: self.presentViewController(alertController, animated : true, completion : nil) 所以,一個簡單的 Alert Dialog 完整的程式如下:let alertController = UIAlertController(title : "My First App", message : "Hello,World!", preferredStyle : UIAlertControllerStyle.Alert) let alertAction = UIAlertAction(title : "OK", style : UIAlertActionStyle.Default, handler : nil ) alertController.addAction(alertAction) self.presentViewController(alertController, animated : true, completion : nil)
Refernce: 1. UIAlertController, https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIAlertController_class/#//apple_ref/swift/enum/c:@E@UIAlertControllerStyle 2. UIAlertAction, https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIAlertAction_Class/ 3. UIViewController, https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIViewController_Class/index.html#//apple_ref/occ/instm/UIViewController/presentViewController:animated:completion:
“Those who are in love with practice without knowledge are like the sailor who gets into a ship without rudder or compass and who never can be certain [where] he is going. Practice must always be founded on sound theory.” by Leonardo da Vinci
2015年9月1日 星期二
【Swift 筆記 Draft】UIAlertController 製作
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言