我们有办法阻止for循环吗?
我有一个循环在里面,它向用户询问一个对话框。我想在用户按OK或取消后暂停循环。
有可能吗?
因为当你有很多循环时,循环一个alertController看起来真的很难看。
for request in friendRequests
{
let alertController = UIAlertController(title: "Friend Request", message: "Would you like to accept this friend request?", preferredStyle: UIAlertControllerStyle.Alert);
let cancelAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil);
let confirmAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil);
alertController.addAction(cancelAction);
alertController.addAction(confirmAction);
//How do we block or wait until user press a button??
self.navigationController.presentViewController(alertController);
}
有什么想法?谢谢
答案 0 :(得分:3)
使用递归函数而不是循环
示例强>
i
答案 1 :(得分:1)
不是创建循环,而是实现一个在用户决定后调用自身的逻辑方法。
更改方法实现,如:
func showAlert(var requestIndex : Int)
{
if (requestIndex < friendRequests.count)
{
var request = friendRequests[requestIndex]
requestIndex++
let alertController = UIAlertController(title: "Friend Request", message: "Would you like to accept this friend request?", preferredStyle: UIAlertControllerStyle.Alert);
let cancelAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler:{ action in
showAlert(requestIndex)
});
let confirmAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { action in
showAlert(requestIndex)
});
alertController.addAction(cancelAction);
alertController.addAction(confirmAction);
//How do we block or wait until user press a button??
self.navigationController.presentViewController(alertController);
}
}
最初调用方法如:
showAlert(0);