用户点击textField外部时关闭键盘

时间:2015-02-24 19:20:05

标签: ios objective-c uitextfield

当用户选择textFiled以外的其他内容时,我正在尝试关闭键盘。我尝试了以下方法:

- (void)viewDidLoad {
    mytextField1.delegate = self;
    mytextFiled2.delegate = self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];    
}

这不起作用。然后,我在[... resignFirstResponder]中尝试touchesBagan,但这也无效。难道我做错了什么?为什么这不起作用?

3 个答案:

答案 0 :(得分:0)

您是否尝试在文本字段的超级视图中添加UITapGestureRecognizer来解除键盘?

答案 1 :(得分:0)

向视图添加点按手势(不是文本字段),以便您知道某人何时点按该视图。

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped)];
[self.view addGestureRecognizer:tap];

然后,当调用该方法时,请先让第一响应者解除键盘。

- (void)viewTapped
{
    if (self.textField.isFirstResponder) {
        [self.textField resignFirstResponder];
    }
}

答案 2 :(得分:0)

您可以使用UITapGestureRecognizer。并且还将当前聚焦的TextField保存在activeTF中。您需要将当前视图控制器设置为UITextField的委托。

UITextField *activeTF;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    .......

    UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:dismissTap];
}


- (void)dismissKeyboard {
    if (activeTF) {
        [activeTF resignFirstResponder];
    }
}

#pragma mark - TextField Delegate

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
    activeTF = sender;
}

- (void)textFieldDidEndEditing:(UITextField *)sender
{
    activeTF = nil;
}