0%

[swift] UIAlertController

  • APP常常有一種狀況是當使用者按下某個選項時,從下面滑出更多的選項讓它做進一步動作,例如在iphone的照片點選垃圾桶時

  • 在IOS 8中多了一個UIAlertController的類別來取代UIAlerView,實際作法如下
    首先將程式碼加到viewDidAppear,否則無法顯示效果,原因請看IOS生命週期的說明點我 ```swift
    override func viewDidAppear(animated: Bool) {

      //建立UIAlertController
      let quetion = UIAlertController(title: nil, message: "What Do u want?", preferredStyle: .ActionSheet);
      //新增選項
      let callaction = UIAlertAction(title: "call xxx", style: .Default , handler:nil);
      //把選項加到UIAlertController
      quetion.addAction(callaction);
      //Show
      self.presentViewController(quetion, animated: true, completion: nil);
    

    }

1
2
3
4
5
執行看到的結果如下圖
[![](http://3.bp.blogspot.com/-FSopEARqG_0/VP1Oau8suBI/AAAAAAAAEhc/v6cpxkt6bWc/s400/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%2B2015-03-09%2B%E4%B8%8B%E5%8D%883.39.39.png)](http://3.bp.blogspot.com/-FSopEARqG_0/VP1Oau8suBI/AAAAAAAAEhc/v6cpxkt6bWc/s1600/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%2B2015-03-09%2B%E4%B8%8B%E5%8D%883.39.39.png)
* 如果將ActionSheet改成Alert,則結果 ```swift
let quetion = UIAlertController(title: nil, message: "What Do u want?", preferredStyle: .Alert);

  • 如果更進階一些,在選擇選項後有些回應時
    我們拉一個label到ViewController裡面來,並且在按下call xxx選項時,把label的字樣給改變 ```swift
    class AlertViewController: UIViewController {
    @IBOutlet weak var showaction: UILabel!
    override func viewDidLoad() {
      super.viewDidLoad();
    
    }
    override func viewDidAppear(animated: Bool) {
      let quetion = UIAlertController(title: nil, message: "What Do u want?", preferredStyle: .Alert);
      let callaction = UIAlertAction(title: "call xxx",style: .Default, handler:{
          (action:UIAlertAction!) -> Void in
          self.showaction.text = "Do call xxx";
      });
      quetion.addAction(callaction);
      self.presentViewController(quetion, animated: true, completion: nil);
    
    }
    }

```
執行看看吧!!