首页 > 代码库 > UIScrollView添加手势显示和隐藏键盘

UIScrollView添加手势显示和隐藏键盘

大概思路:本身textField点击键盘弹出,点击手势后自身view结束编辑,手势设为no,再点击textField时键盘弹出,这时用通知通知手势交互为yes即可

首先在.h文件中添加手势协议<UIGestureRecognizerDelegate>

在.m文件中声明一个手势指针

UITapGestureRecognizer * _gesture;

 _gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidesKeyboard)];
    _gesture.enabled = NO;//最开始手势设为no
    [self.view addGestureRecognizer:_gesture];

隐藏键盘的方法

- (void)hidesKeyboard{
    [self.view endEditing:YES];
    _gesture.enabled = NO;
}

键盘显示我用了通知结合手势来的

先注册一个通知,

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];

完成通知的方法就是把手势设为yes即可

- (void)keyboardWillShow {
    _gesture.enabled = YES;
}

UIScrollView添加手势显示和隐藏键盘