UIAlertcontroller在自定义TableViewCell WITH返回值

时间:2016-01-05 07:10:31

标签: ios swift2 xcode7 uialertcontroller

我已经通过UIAlertControllerTableViewCell搜索了protocols取代delegates的类似答案。我得到了那部分工作。但我在UIAlertController中有两个动作。其中一个确认操作并返回true,另一个按钮取消并返回false。

我可以成功展示UIAlertController,但程序只是运行我的代码并忽略确认按钮中的逻辑。我认为这是因为委托/协议方法在并行/异步中运行delegate方法,并且不会等待返回值。

以下是我的自定义TableViewCell中的代码:

var unattend: Bool!
let customAlert = UIAlertController(title: "Not going anymore?", message: "Event will disappear from this list, confirm?", preferredStyle: UIAlertControllerStyle.Alert)
let nevermindAction = UIAlertAction(title: "Nevermind", style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
    unattend = false
}
let unattendAction = UIAlertAction(title: "Confirm unattending", style: UIAlertActionStyle.Destructive) { (action: UIAlertAction) -> Void in
    unattend = true
}
customAlert.addAction(nevermindAction)
customAlert.addAction(unattendAction)

self.delegate.goingCancelled(customAlert, unattend: unattend)) 

这是我的协议:

protocol GoingCancelledDelegate {
func goingCancelled(alert: UIAlertController) -> Bool
}

这是我的TableViewController中的代码,是的,我在类定义中输入了GoingCancelledDelegate,只是没有复制并粘贴在这里:

func goingCancelled(alert: UIAlertController) -> Bool {
    presentViewController(alert, animated: true) { () -> Void in
    }
}

因此警报显示,但我的UITableViewCell代码不等待返回值处理其他逻辑。任何提示/建议/帮助将不胜感激!提前谢谢!

1 个答案:

答案 0 :(得分:1)

因为您在没有确认操作的情况下调用self.delegate.goingCancelled(customAlert, unattend: unattend))执行此操作:

var unattend: Bool!
 let customAlert = UIAlertController(title: "Not going anymore?", message: "Event will disappear from this list, confirm?", preferredStyle: UIAlertControllerStyle.Alert)
 let nevermindAction = UIAlertAction(title: "Nevermind", style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
    unattend = false
}
 let unattendAction = UIAlertAction(title: "Confirm unattending", style: UIAlertActionStyle.Destructive) { (action: UIAlertAction) -> Void in
    unattend = true
 self.delegate.goingCancelled(customAlert, unattend: unattend)) 
}
customAlert.addAction(nevermindAction)
customAlert.addAction(unattendAction)