增加可点击区域

2018-02-11  本文已影响32人  konglei

UIView+hitTest.h

#import <UIKit/UIKit.h>

@interfaceUIView (enlargeZone)

- (void)setEnlargeEdge:(UIEdgeInsets)edge;

@end

UIView+hitTest.m

#import "UIView+enlargeZone.h"

@implementationUIView (enlargeZone)

staticchartopEdgeKey;

staticcharrightEdgeKey;

staticcharbottomEdgeKey;

staticcharleftEdgeKey;

- (void) setEnlargeEdge:(UIEdgeInsets)edge{

    objc_setAssociatedObject(self, &topEdgeKey, [NSNumber numberWithFloat:edge.top], OBJC_ASSOCIATION_COPY_NONATOMIC);

    objc_setAssociatedObject(self, &rightEdgeKey, [NSNumber numberWithFloat:edge.right], OBJC_ASSOCIATION_COPY_NONATOMIC);

    objc_setAssociatedObject(self, &bottomEdgeKey, [NSNumber numberWithFloat:edge.bottom], OBJC_ASSOCIATION_COPY_NONATOMIC);

    objc_setAssociatedObject(self, &leftEdgeKey, [NSNumber numberWithFloat:edge.left], OBJC_ASSOCIATION_COPY_NONATOMIC);

}

- (CGRect) enlargedRect

{

    NSNumber* topEdge = objc_getAssociatedObject(self, &topEdgeKey);

    NSNumber* rightEdge = objc_getAssociatedObject(self, &rightEdgeKey);

    NSNumber* bottomEdge =objc_getAssociatedObject(self, &bottomEdgeKey);

    NSNumber* leftEdge = objc_getAssociatedObject(self, &leftEdgeKey);

    if(topEdge && rightEdge && bottomEdge && leftEdge)

    {

        returnCGRectMake(self.bounds.origin.x- leftEdge.floatValue,

                          self.bounds.origin.y- topEdge.floatValue,

                          self.bounds.size.width+ leftEdge.floatValue+ rightEdge.floatValue,

                          self.bounds.size.height+ topEdge.floatValue+ bottomEdge.floatValue);

    }

    else

    {

        returnself.bounds;

    }

}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event

{

    CGRectbounds = [selfenlargedRect];

    returnCGRectContainsPoint(bounds, point);

}

@end

上一篇下一篇

猜你喜欢

热点阅读