当文本字段在时,UIAlertView clickedButtonAtIndex未被调用

时间:2015-10-01 02:04:59

标签: ios delegates uialertview

当我有以下代码时,将调用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];

为什么会这样?

1 个答案:

答案 0 :(得分:0)

确保您在视图控制器中添加了<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在iOS 8及更高版本中不再可用/支持所以在这个地方使用UIAlertViewController,如何使用UIAlertViewController的示例请参阅tutorial