美文网首页
点击ScrollView时收起键盘

点击ScrollView时收起键盘

作者: 狗娃_ | 来源:发表于2017-03-02 10:46 被阅读775次

有时当self.view上添加了scrollview时,在

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 中调用 [self.view endEditing:YES]时;并不能收起键盘,因为此时touch是触发在scrollView上. 所以要想点击scrollView的空白区域来收起键盘时,可以通过写一个scrollView的扩展.代码如下:

- (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];
        }
    }
}
 

在需要此功能的页面控制器内添加以下代码:

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

相关文章

网友评论

      本文标题:点击ScrollView时收起键盘

      本文链接:https://www.haomeiwen.com/subject/gxdhgttx.html