iOSはUIButtonのクリック範囲を拡大

1564 ワード

実際の開発では、ButtonFrameが小さすぎるため、クリック範囲も小さく、Buttonのクリック範囲を大きくする必要がある場合があるが、ButtonFrameを変更する必要はない.UIViewには一つの方法があります
 // default returns YES if point is in bounds
- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event;  

この方法は、クリック範囲がこのviewの場合、YESを返し、そうでなければNOを返す.
新しい分類を作成し、新しい属性を追加できます.記録には範囲の拡大が必要です.
@property (nonatomic, assign) CGFloat expandSize; /**<   */

.mファイルの実装に以下の方法を追加
- (void)setExpandSize:(CGFloat)expandSize {
    
    objc_setAssociatedObject(self, @selector(setExpandSize:), @(expandSize), OBJC_ASSOCIATION_ASSIGN);
}

- (CGFloat)expandSize {
    
    return [objc_getAssociatedObject(self, @selector(setExpandSize:)) floatValue];
}

- (CGRect)expandRect {
    
    return CGRectMake(self.bounds.origin.x - self.expandSize,
                      self.bounds.origin.y - self.expandSize,
                      self.bounds.size.width + 2 * self.expandSize,
                      self.bounds.size.height + 2 * self.expandSize);
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    
    CGRect buttonRect = [self expandRect];
    
    if (CGRectEqualToRect(buttonRect, self.bounds)) {
        return [super pointInside:point
                        withEvent:event];
    }
    
    return  CGRectContainsPoint(buttonRect, point);
}

これにより、ButtonFrameを変更することなく、Buttonのクリック範囲が拡大される.