2012-07-17 126 views
0

我創建了一個Master-Detail Splitview應用程序,我在insertNewObject方法中使用UIAlertView來讓用戶爲添加到主視圖的新對象定義標題。我已經使用Warkst的這個問題linky的代碼和指南。使用UIAlert查看讓用戶輸入標題

我的問題是,當調用alert視圖時,insertNewObject函數的其餘部分繼續運行,因此創建一個空白標題的新對象,因爲它在AlertView甚至有機會出現之前運行完畢。

我使用的代碼如下,第一種方法是insertNewObject,第二種方法是按下按鈕時AlertView調用的方法。 newTitle是一個全局變量。

- (void)insertNewObject:(id)sender 
{ 
    //Make sure clear before we start, also make sure initalized (double redundancy with clear statement at end) 
    newTitle = @""; 

    //New Title pop up UIAlert View 
    UIAlertView * alert = [[UIAlertView alloc] 
          initWithTitle:@"New Object" 
          message:@"Please enter a name for object" 
          delegate:self 
          cancelButtonTitle:@"Create" 
          otherButtonTitles:nil]; 

    alert.alertViewStyle = UIAlertViewStylePlainTextInput; 

    UITextField * alertTextField = [alert textFieldAtIndex:0]; 

    alertTextField.keyboardType = UIKeyboardTypeDefault; 

    alertTextField.placeholder = @"Enter a new title"; 
    [alert show]; 

    //Create and enter new object. 
    if (!_objects) 
    { 
     _objects = [[NSMutableArray alloc] init]; 
    } 

    [_objects insertObject:newTitle atIndex:0]; 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; 

    //Clear newTitle for use next time 
    newTitle = @""; 
} 

UIAlertView中鍵單擊方法

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
    newTitle = [[alertView textFieldAtIndex:0] text]; 
} 

回答

1

你想要做的UIAlertViewDelegate方法alertView:clickedButtonAtIndex:你的對象創建因爲(你是否注意到)調用顯示警報DOS不能阻擋的休息方法執行。

此外,如果它是相關的,您可能希望讓用戶通過添加一個附加按鈕來取消操作。