2015年9月3日 星期四

第一個程式:UIAlertController 製作 (2)

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)

後記: 很多書籍在解釋 iPhone 的程式時會逐條解釋,但當下似乎只知道說明的部分,至於該怎麼寫還是很虛。我試著由概念出發,即程式不是重點,而是我到底想開發什麼,然後試著去找相關對應的工具。每個工具在 Apple 的 Developer 網站都有詳細的說明。依據這思維,開發 iPhone 就變得相當容易些。 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:

沒有留言:

張貼留言

prettyPrint();