iOS NavigationBar backBarButtonItem 点击区域过大解决方案

写在前面:

iOS10以下,点击backBarButtonItem按钮的时候,点击区域过大(点击NavigationBar区域外也相应点击事件)。一般情况这种问题也不能影响什么,但是如果你的App在NavigationBar下正好有一个需要响应触摸事件的时候,就会导致该控件的触摸区域缩小。

图中红色区域点击响应返回按钮事件.png

实现思路:

创建UINavigationBar的类别(Category),重写- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event方法,判断点击区域是否位于UINavigationBar的Frame内。

核心代码:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    int errorMargin = 5;
    CGRect smallerFrame = CGRectMake(0 , 0 - errorMargin, self.frame.size.width, self.frame.size.height);
    BOOL isTouchAllowed =  (CGRectContainsPoint(smallerFrame, point) == 1);
    
    if (isTouchAllowed) {
        self.userInteractionEnabled = YES;
    } else {
        self.userInteractionEnabled = NO;
    }
    return [super hitTest:point withEvent:event];
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容