2015-06-15 55 views
0

是有我們的方式來阻止一個for循環?封閉循環中使用UIAlertController

我有一個循環,在它裏面,它向用戶提供一個對話框。我希望它在用戶按下確定或取消後暫停循環。

可能嗎?

因爲循環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); 
} 

有什麼想法?由於

回答

3

使用遞歸函數,而不是循環

var name:[String] = ["abcd","efgh","ijkl","mnop","qrst","uvwx"] 
self.friendReuqest(name, index: 0) 

func friendReuqest(name:[String],index:Int) 
{ 
    if index < name.count 
    { 
     let alertController = UIAlertController(title: name[index], message: "Would you like to accept this friend request?", preferredStyle: UIAlertControllerStyle.Alert) 

     let cancelAction: UIAlertAction = UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Cancel){ (action: UIAlertAction!) -> Void in 
      // do stuff here when press cancel 
     } 

     let confirmAction: UIAlertAction = UIAlertAction(title: "Add", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in 
      self.friendReuqest(name, index: (index + 1)) 
     } 

     alertController.addAction(cancelAction) 
     alertController.addAction(confirmAction) 
     self.presentViewController(alertController, animated: true, completion: nil) 
    } 
} 
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);