在 UITextField UIControlEventEditingDidBegin 上调用 UIAlertView 关闭键盘

Calling UIAlertView on UITextField UIControlEventEditingDidBegin dismisses keyboard

我注意到一些非常奇怪的行为。我想在选择 UITextField 时显示 UIAlertView:

[self.addressTextField addTarget:self action:@selector(addressTextFieldSelected) forControlEvents:UIControlEventEditingDidBegin];

正在调用的方法是:

- (void)addressTextFieldSelected {

    if (!geoPoint) {

        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Text" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];

    }

}

触摸 textField 时,键盘确实开始向上滑动。但是,当 alertView 出现时,键盘消失了。选择 'OK' 并关闭 alertView 后,文本字段的键盘向上滑动。

编辑

在其他人的帮助下,我创建了这个解决方法,尽管我对键盘一开始就消失有点不满意。

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    if (textField.tag == 2) {

        if (!geoPoint && !justShowedGeoPointAlert) {

            showingGeoPointAlert = YES;

            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Make sure to geotag this address." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertView show];

            return NO;

        } else {

            justShowedGeoPointAlert = NO;

        }

    }

    return YES;

}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {

    if (showingGeoPointAlert) {

        justShowedGeoPointAlert = YES;
        showingGeoPointAlert = NO;
        [self.addressTextField becomeFirstResponder];

    }

}

UIAlertView 的代码移至 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField,如果 return NO 键盘将不会出现

实现以下 UITextField 的委托方法:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;

在此方法中显示警报视图,return在此方法中为否,将不显示键盘。

然后实现以下UIAlertView的委托方法:

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex;

在此方法中,显示键盘:

[self.addressTextField becomeFirstResponder];

尝试如下操作:

@interface ViewController () <UIAlertViewDelegate, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) UITextField *selectedTextField;

@end

@implementation ViewController

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.selectedTextField) {
        self.selectedTextField = nil;
        return YES;
    }

    self.selectedTextField = textField;

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Text" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];

    return NO;
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
    [self.selectedTextField becomeFirstResponder];
}

@end