文本字段位于时不调用 UIAlertView clickedButtonAtIndex

UIAlertView clickedButtonAtIndex not called when text field is in

当我有以下代码时,将调用 clickedButtonAtIndex 委托方法:

UIAlertView * alertTextField = [[UIAlertView alloc] initWithTitle:@"Post To Facebook" message:@"What would you like the post to say?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Continue", nil];
        alertTextField.tag = 2;
        [alertTextField show];

但是当我在 UIAlertViewStylePlainTextInput 中添加时,委托方法没有被调用。

 UIAlertView * alertTextField = [[UIAlertView alloc] initWithTitle:@"Post To Facebook" message:@"What would you like the post to say?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Continue", nil];
        [alertTextField setAlertViewStyle:UIAlertViewStylePlainTextInput];
        alertTextField.tag = 2;
        [alertTextField show];

这是为什么?

确保您在视图控制器中添加了 <UIAlertViewDelegate> 而您忘记添加 alertTextField.delegate = self; 然后实现委托以接收事件。

UIAlertView * alertTextField = [[UIAlertView alloc] initWithTitle:@"Post To Facebook" message:@"What would you like the post to say?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Continue", nil];
[alertTextField setAlertViewStyle:UIAlertViewStylePlainTextInput];
alertTextField.delegate = self; // you forget to add this line 
alertTextField.tag = 2;
[alertTextField show];


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

UIAlertView no longer available/support in iOS 8 and above so in this place use UIAlertViewController, example for how to use UIAlertViewController see this tutorial