2016-02-02 41 views
2

如果我在控制器上有多個AlertView,如何讓它只顯示最後一個AlertView,如果它們全部被觸發?請看下面的代碼:Swift如果有多個AlertView推送,只顯示一個AlertView

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.getAPI1() 
    self.getAPI2() 
    self.getAPI3() 
} 

func getAPI1() { 
    do { 
     // try ... Get API Process 
    } catch { 
     let alertView = UIAlertView(title: "ERROR", message: "There is an error on getAPI1()", delegate: nil, cancelButtonTitle: "OK") 
     alertView.show() 
    } 
} 

func getAPI2() { 
    do { 
     // try ... Get API Process 
    } catch { 
     let alertView = UIAlertView(title: "ERROR", message: "There is an error on getAPI2()", delegate: nil, cancelButtonTitle: "OK") 
     alertView.show() 
    } 
} 

func getAPI3() { 
    do { 
     // try ... Get API Process 
    } catch { 
     let alertView = UIAlertView(title: "ERROR", message: "There is an error on getAPI3()", delegate: nil, cancelButtonTitle: "OK") 
     alertView.show() 
    } 
} 

由於getAPI1,getAPI2和getAPI3需要,如果他們中的一個越來越錯誤被執行不管,怎麼只顯示最後AlertView?謝謝。

+0

改爲使用UIAlertController,它將遵循正常的UIViewController邏輯。 (即:presentViewController:animated :),你可以以任何你想要的順序來呈現它們 – ambientlight

回答

1

您可以有一個變量來存儲當前正在激活和顯示的警報。

var activeAlert : UIAlertView! = nil 

每次顯示警報時,檢查是否有警報顯示在前。你可以這樣檢查它

if nil != activeAlert { 
    activeAlert.dismissWithClickedButtonIndex(-1, animated: false) 
    //show your new alert here 
} 

這樣就可以確保總是顯示最後的警報。確保您正在執行UIAlertViewDelegate協議的alertView:clickedButtonAtIndex:方法。此外,UIAlertView已從iOS 9.0中棄用,因此我建議您使用UIAlertViewController而不是