UIAlertView输入提示

时间:2014-05-18 13:53:55

标签: ios objective-c uialertview

我在我的应用中需要输入提示,我已尝试过这个

// Create a new item
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"New item" message:@"Enter a name for the item" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Add", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];

然后像这样处理它:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
// The user created a new item, add it
if (buttonIndex == 1) {
    // Get the input text
    NSString *newItem = [[alertView textFieldAtIndex:0] text];
}
}

但它看起来不像clickedButtonAtIndex被调用,为什么?

亲切的问候, 埃里克

2 个答案:

答案 0 :(得分:7)

您需要设置委托。

alert.delegate = self; //Or some other object other than self

或者,当您初始化警报时:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"New item" 
                                                message:@"Enter a name for the item"
                                               delegate:self
                                      cancelButtonTitle:@"Cancel"
                                      otherButtonTitles:@"Add", nil];

答案 1 :(得分:0)

未调用方法,因为您未设置委托。
将自己作为代理人传递,以便获得对它的引用。

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"New item" message:@"Enter a name for the item" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Add", nil];