0

Master-Detail Splitviewアプリを作成していUIAlertViewて、insertNewObjectメソッドでを使用して、マスタービューに追加される新しいオブジェクトのタイトルをユーザーが定義できるようにしています。Warkstによるこの質問のリンクのコードとガイドを使用しました。

私の問題は、アラートビューが呼び出されると、残りのinsertNewObject関数が引き続き実行されるため、AlertViewが表示される前に実行が終了するため、タイトルが空白の新しいオブジェクトが作成されることです。

私が使用しているコードは次のとおりです。最初のメソッドは次のメソッドでinsertNewObject、2番目のメソッドはボタンが押されたときに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];
}
4

1 に答える 1

1

(お気づきのように)アラートを表示する呼び出しは、メソッドの残りの部分の実行をブロックしないため、UIAlertViewDelegateメソッドでオブジェクトの作成を行う必要があります。alertView:clickedButtonAtIndex:

また、関連性がある場合は、ボタンを追加して、ユーザーがアクションをキャンセルできるようにすることもできます。

于 2012-07-17T02:13:56.337 に答える