美文网首页
UIControl扩大响应区域

UIControl扩大响应区域

作者: 张_何 | 来源:发表于2018-11-09 10:36 被阅读0次

OC版本

声明

#import <UIKit/UIKit.h>
@interface UIControl (EnlargeEdge)
-(void)setEnlargeWithTop:(CGFloat)top left:(CGFloat)left bottom:(CGFloat)bottom right:(CGFloat)right;
@end

实现

#import <objc/runtime.h>
#import "UIControl+EnlargeEdge.h"

static char topKey;
static char bottomKey;
static char leftKey;
static char rightKey;

@implementation UIControl (EnlargeEdge)

- (void)setEnlargeWithTop:(CGFloat)top left:(CGFloat)left bottom:(CGFloat)bottom right:(CGFloat)right {
    objc_setAssociatedObject(self, &topKey,   [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_COPY_NONATOMIC);
    objc_setAssociatedObject(self, &bottomKey,   [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_COPY_NONATOMIC);
    objc_setAssociatedObject(self, &leftKey,   [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_COPY_NONATOMIC);
    objc_setAssociatedObject(self, &rightKey,   [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (CGRect)enlargedRect {
    NSNumber* topEdge    = objc_getAssociatedObject(self, &topKey);
    NSNumber* rightEdge  = objc_getAssociatedObject(self, &rightKey);
    NSNumber* bottomEdge = objc_getAssociatedObject(self, &bottomKey);
    NSNumber* leftEdge   = objc_getAssociatedObject(self, &leftKey);
    
    if (topEdge && rightEdge && bottomEdge && leftEdge) {
        return CGRectMake(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 {
        return self.bounds;
    }
}

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

@end

Swift 版本

import Foundation
import UIKit

/// 可以扩大点击范围的Button
class SJEnlargeTouchAreBtn: UIButton {
    public var enarlgeAreEdge: UIEdgeInsets = UIEdgeInsets.zero
    
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        super.point(inside: point, with: event)
        let area = CGRect.init(x: self.bounds.origin.x - enarlgeAreEdge.left, y: self.bounds.origin.y - enarlgeAreEdge.top, width: self.bounds.size.width + enarlgeAreEdge.left + enarlgeAreEdge.right, height: self.bounds.size.height + enarlgeAreEdge.top + enarlgeAreEdge.bottom)
        return area.contains(point) 
    }
}

相关文章

网友评论

      本文标题:UIControl扩大响应区域

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