iOS开发之点击空白处退出键盘

一、以前使用的退出键盘方法

UIScrollView 上如果有UITextField的话,结束编辑(退出键盘)直接用touchesBegan方法无效,需要再给UIScrollView加一个分类,重写几个方法。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesBegan:touches withEvent:event];
    [super touchesBegan:touches withEvent:event];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesMoved:touches withEvent:event];
    [super touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesEnded:touches withEvent:event];
    [super touchesEnded:touches withEvent:event];
}

一般都使用这个方法,但是这样写是有问题的,在_使用系统手写键盘时会出现奔溃问题。_
手写键盘输入时,会调用UIScrollView的- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;这个分类方法,self的类型是UIKBCandidateCollectionView,一种系统没有暴露出来的类型,应该是UIScrollView的一个子类,所以系统会奔溃。

二、增加判断避免手写输入奔溃

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self isMemberOfClass:[UIScrollView class]]) {
        
    } else {
        [[self nextResponder] touchesBegan:touches withEvent:event];
        if ([super respondsToSelector:@selector(touchesBegan:withEvent:)]) {
            [super touchesBegan:touches withEvent:event];
        }
    }
    
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self isMemberOfClass:[UIScrollView class]]) {
        
    } else {
        [[self nextResponder] touchesMoved:touches withEvent:event];
        if ([super respondsToSelector:@selector(touchesBegan:withEvent:)]) {
            [super touchesMoved:touches withEvent:event];
        }
    }
    
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self isMemberOfClass:[UIScrollView class]]) {
        
    } else {
        [[self nextResponder] touchesEnded:touches withEvent:event];
        if ([super respondsToSelector:@selector(touchesBegan:withEvent:)]) {
            [super touchesEnded:touches withEvent:event];
        }
    }
}

这个方法UIscrollview没有问题,但是在UItableview上的取消键盘会失效

三、点击手势退出键盘

使用点击手势可以避免问题

UITapGestureRecognizer *tapView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchViewCancelKeyBoard:)];
    tapView.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapView];
- (void)touchViewCancelKeyBoard:(UITapGestureRecognizer *)tap {
    [self.TextField resignFirstResponder];
}

四、scrollview自带的属性

scsrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

其中keyboardDismissMode是UIScrollView的属性,
它的值除了UIScrollViewKeyboardDismissModeNone,
UIScrollViewKeyboardDismissModeOnDrag,表示拖动时键盘消失,
UIScrollViewKeyboardDismissModeInteractive,表示键盘可以随着手指下滑而移出屏幕。

希望这个内容对大家有用

你可能感兴趣的:(iOS开发)