美文网首页
扩大视图点击区域

扩大视图点击区域

作者: 快乐的小梁同学 | 来源:发表于2016-04-26 17:39 被阅读163次

    导语


    在工作中,经常创建一些视图(比如button),这时button很小,点击时,总感到不精准,有时我们会在这个小button上放一个大一点的透明button。但是有没有好烦燥呀。

    分类介入UIView+ExtendTouchRect

    写这个分类,是受到一篇blog的启发。在这里感谢他的作者,作者名我忘记了。
    分类写好后,一行代码解决问题
    

    使用代码

    self.button.touchExtendInset = UIEdgeInsetsMake(-10, -10, -10, -10)

    实现代码如下

    void Swizzle(Class c, SEL orig, SEL new) { Method origMethod = class_getInstanceMethod(c, orig); Method newMethod = class_getInstanceMethod(c, new); if (class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))){ class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod)); } else { method_exchangeImplementations(origMethod, newMethod); } }
    @implementation UIView (ExtendTouchRect)
    + (void)load { Swizzle(self, @selector(pointInside:withEvent:), @selector(myPointInside:withEvent:)); }
    - (BOOL)myPointInside:(CGPoint)point withEvent:(UIEvent *)event { if (UIEdgeInsetsEqualToEdgeInsets(self.touchExtendInset, UIEdgeInsetsZero) || self.hidden || ([self isKindOfClass:UIControl.class] && !((UIControl *)self).enabled)) { return [self myPointInside:point withEvent:event]; // original implementation } CGRect hitFrame = UIEdgeInsetsInsetRect(self.bounds, self.touchExtendInset); hitFrame.size.width = MAX(hitFrame.size.width, 0); // don't allow negative sizes hitFrame.size.height = MAX(hitFrame.size.height, 0); return CGRectContainsPoint(hitFrame, point); }
    static char touchExtendInsetKey;
    - (void)setTouchExtendInset:(UIEdgeInsets)touchExtendInset { objc_setAssociatedObject(self, &touchExtendInsetKey, [NSValue valueWithUIEdgeInsets:touchExtendInset], OBJC_ASSOCIATION_RETAIN); }
    - (UIEdgeInsets)touchExtendInset { return [objc_getAssociatedObject(self, &touchExtendInsetKey) UIEdgeInsetsValue]; }
    @end

    相关文章

      网友评论

          本文标题:扩大视图点击区域

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