在UITextField上调用UIAlertView UIControlEventEditingDidBegin解除键盘

时间:2015-04-30 11:05:37

标签: ios objective-c uitextfield uialertview

我注意到一些非常奇怪的行为。我想在选择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出现时,键盘会解散。选择“确定”并关闭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];

    }

}

3 个答案:

答案 0 :(得分:3)

实现以下UITextField的委托方法:

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

在此方法中显示警报视图,并在此方法中返回NO,键盘将不会显示。

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

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

在此方法中,显示键盘:

[self.addressTextField becomeFirstResponder];

答案 1 :(得分:1)

UIAlertView的代码移至- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField,如果返回NO键盘将不会显示

答案 2 :(得分:1)

尝试以下内容:

@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