2016-03-04 50 views
3

我想用一個觸發父視圖控制器關閉的選項向用戶展示一個簡單的UIAlertController。這裏是我使用的代碼:如何從UIAlertController的UIAlertAction處理程序中關閉UIViewController?

let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) 

    alert.addAction(UIAlertAction(title: "Close View", style: UIAlertActionStyle.Destructive, handler: { 
     action in 

     self.dismissViewControllerAnimated(true, completion: nil) 
    })) 

    alert.addAction(UIAlertAction(title: "CANCEL", style: UIAlertActionStyle.Cancel, handler: nil)) 

    self.presentViewController(alert, animated: true, completion: nil) 

它沒有任何作用。執行「Close View」處理程序後,呈現警報的視圖控制器仍然存在。

我也在UIAlertAction動作塊中試過self.navigationController?.dismissViewControllerAnimated(true, completion: nil),但那也沒有效果。

回答

4

使用

self.navigationController?.popViewControllerAnimated(true) 
根據需要並關閉其顯示警報的視圖控制器

代替

self.dismissViewControllerAnimated(true, completion: nil) 

作品。

0

您使用presentViewController來顯示警報。因此,如果您使用self.dismissViewController,它只會取消警報,而不是父視圖控制器。如果你試圖隱藏父視圖控制器,你可以創建一個寬度高度等於self.view的視圖,並給它黑色。然後使用view.addSubView在你想要的任何時候添加它。

相關問題