2017-08-11 95 views
0

我想要做一些操作並在任何UIAlertController因爲用戶點擊其中一個警報按鈕而退出之前和之後呈現一些UI(動畫完成)。當UIAlertController在按下按鈕時被取消通知

我如何得到通知用戶在我的UIAlertController中按下了一些按鈕,它將被解僱然後被解僱?

在文檔中,建議不要繼承UIAlertController的子類。我仍然嘗試過我的運氣子類化,認爲它本身可能在內部調用func dismiss(animated flag: Bool, completion: (() -> Void)? = nil)。類似於self.dismiss(...,但在iOS10上似乎不是這種情況。

我也嘗試添加「手動」駁回到UIAlertAction處理程序:

let alert = UIAlertController.init(... 
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in 
    alert.dismiss(animated: true, completion: { 
     print("Dismissed") 
    }) 
}) 
alert.addAction(defaultAction) 

但似乎警報按鈕按下之後,但在調用處理程序之前被解僱。無論如何,它不工作。即使它有效,記住將代碼添加到每個UIAlertAction處理程序中也會有點麻煩。

我會很感激任何想法。

+0

爲什麼你不在「defaultAction」塊內做所有需要的東西?無論如何,此阻止警報將被解除。 –

+0

@ biloshkurskyi.ss正如我在我的問題中寫的 - 這很容易出錯,人們可能很容易在某處忘記一個塊。 – iur

回答

0

雖然子類不建議你可以使用一個簡單的子類,像這樣:

class CustomAlertController: UIAlertController { 

    var willDisappearBlock: ((UIAlertController) -> Void)? 
    var didDisappearBlock: ((UIAlertController) -> Void)? 

    override func viewWillDisappear(_ animated: Bool) { 
     willDisappearBlock?(self) 
     super.viewWillDisappear(animated) 
    } 

    override func viewDidDisappear(_ animated: Bool) { 
     super.viewDidDisappear(animated) 
     didDisappearBlock?(self) 
    } 

} 

然後你可以使用它像這樣:

let alert = CustomAlertController(title: "Alert", message: "This is an alert. Press Yes or No.", preferredStyle: .alert) 
alert.willDisappearBlock = { alert in 
    print("\(alert) will disappear") 
} 
alert.didDisappearBlock = { alert in 
    print("\(alert) did disappear") 
} 

alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (yesAction) in 
    print("User tapped Yes.") 
})) 
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { (yesAction) in 
    print("User tapped No.") 
})) 
present(alert, animated: true) { 
    print("presentCompletion") 
} 

輸出是按以下順序:

  1. 目前完成
  2. 將會消失
  3. 確實 消失
  4. 用戶點擊是。
+0

謝謝。這似乎工作。我希望蘋果公司在內部實施中不會改變任何事情。 – iur