2016-06-09 120 views
0

我需要一個UIAlert的幫助。我收到一個錯誤"UIAlertController can only have one action with a style of UIAlertActionStyleCancel"。我知道這是因爲我在該功能之外啓動了此警報,但不確定如何解決該警報。如何在if條件下訪問警報?以編程方式取消警報Swift

let alertView = UIAlertController(title: "Blah", message: "", preferredStyle: UIAlertControllerStyle.Alert) 
@IBAction func blahButtonPressed(sender: AnyObject) {   

     alertView.addAction(UIAlertAction(title: "Do Something", style: .Default, handler: { (action: UIAlertAction!) in 
      // I have code here 
     })) 

     alertView.addAction(UIAlertAction(title: "Do Something 2", style: .Default, handler: { (action: UIAlertAction!) in 
      // I have code here 
     })) 

     alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in 
      // I have code here 
     })) 

     presentViewController(alertView, animated: true, completion: nil) 

} 

代碼後來我通過藍牙獲取值,需要解除警報,如果值低於80

if blah < 80 { 
alertView.dismissViewControllerAnimated(true, completion: nil) 
} 
+0

blahButtonPressed被執行了多次?錯誤消息聽起來像你添加「取消」多次。 –

+0

不,只是一個按鈕。我只按一次,而不是在其他地方打電話。 – KotaBear233

回答

0

這是我如何固定它,如果有人來翻過這一點。

var newAlert: AnyObject? 


@IBAction func blahButtonPressed(sender: AnyObject) {   
    let alertView = UIAlertController(title: "Blah", message: "", preferredStyle: UIAlertControllerStyle.Alert) 
    alertView.addAction(UIAlertAction(title: "Do Something", style: .Default, handler: { (action: UIAlertAction!) in 
     // I have code here 
    })) 

    alertView.addAction(UIAlertAction(title: "Do Something 2", style: .Default, handler: { (action: UIAlertAction!) in 
     // I have code here 
    })) 

    alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in 
     // I have code here 
    })) 

    newAlert = alertView 

     presentViewController(alertView, animated: true, completion: nil) 
} 

//當我需要關閉。如果等於低於80

if blah < 80 { 
    if let newAlertView = newAlert as? UIAlertController { 
     newAlertView.dismissViewControllerAnimated(true, completion: nil) 
    } 
} 
2

我不是100%,但是當你只按一下按鈕時它是否工作?如果是這樣,那麼可能是因爲您在@IBAction內將操作添加到alertView。相反,您可能想要嘗試在@IBAction之外移動UIAlertAction的其他內容,並僅在其內部顯示警報視圖。像這樣:

let alertView = UIAlertController(title: "Blah", message: "", preferredStyle: UIAlertControllerStyle.Alert) 
alertView.addAction(UIAlertAction(title: "Do Something", style: .Default, handler: { (action: UIAlertAction!) in 
     // I have code here 
    })) 

alertView.addAction(UIAlertAction(title: "Do Something 2", style: .Default, handler: { (action: UIAlertAction!) in 
     // I have code here 
    })) 

alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in 
     // I have code here 
    })) 

@IBAction func blahButtonPressed(sender: AnyObject) { 
    presentViewController(alertView, animated: true, completion: nil) 
} 

這樣,UIAlertAction的沒有得到添加了‘blahButton’被按下,每一次(這將導致多個UIAlertAction與‘UIAlertActionStyleCancel’的風格)