扩大Button按钮的点击区域

本文介绍了一个 UIButton 的 Objective-C 扩展,该扩展允许设置按钮的点击区域大小,通过设置四个边距来实现点击区域的扩大,适用于需要调整 UIButton 触发区域的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
//  UIButton+RM.h
//  ProjectManageEx
//
//  Created by mac on 16/7/31.
//  Copyright © 2016年 zhangjian01. All rights reserved.
//

#import

@interface UIButton (RM)

@property (nonatomic, assign)CGFloat enlargedEdge;



- (void)setEnlargedEdgeWithTop:(CGFloat)top left:(CGFloat)left bottom:(CGFloat)bottom right:(CGFloat)right;


@end
//
//  UIButton+RM.m
//  ProjectManageEx
//
//  Created by mac on 16/7/31.
//  Copyright © 2016年 zhangjian01. All rights reserved.
//

#import "UIButton+RM.h"

@implementation UIButton (RM)

static char  topEdgeKey;
static char  leftEdgeKey;
static char  bottomEdgeKey;
static char  rightEdgeKey;

- (void)setEnlargedEdge:(CGFloat)enlargedEdge{
   
    [self setEnlargedEdgeWithTop:enlargedEdge left:enlargedEdge bottom:enlargedEdge right:enlargedEdge];
   
}

- (CGFloat)enlargedEdge{
    return [(NSNumber *)objc_getAssociatedObject(self, &topEdgeKey)floatValue];
}

- (void)setEnlargedEdgeWithTop:(CGFloat)top left:(CGFloat)left bottom:(CGFloat)bottom right:(CGFloat)right{
   
    objc_setAssociatedObject(self, &topEdgeKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, &leftEdgeKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, &bottomEdgeKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, &rightEdgeKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CGRect)enlargedRect{
    NSNumber *topEdge = objc_getAssociatedObject(self, &topEdgeKey);
    NSNumber *leftEdge = objc_getAssociatedObject(self, &leftEdgeKey);
    NSNumber *bottomEdge = objc_getAssociatedObject(self, &bottomEdgeKey);
    NSNumber *rightEdge = objc_getAssociatedObject(self, &rightEdgeKey);
   
    if (topEdge && leftEdge && bottomEdge && rightEdge) {
       
        CGRect enlargedRect = CGRectMake(self.bounds.origin.x - leftEdge.floatValue, self.bounds.origin.y - topEdge.floatValue, self.width + leftEdge.floatValue + rightEdge.floatValue, self.height + topEdge.floatValue + bottomEdge.floatValue);
        return enlargedRect;
    }else{
       
        return self.bounds;
    }
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
   
    if (self.alpha <= 0.01 || !self.userInteractionEnabled || self.hidden) {
        return nil;
    }
    CGRect enlargedRect = [self enlargedRect];
    return CGRectContainsPoint(enlargedRect, point) ? self : nil;
   
}


@end











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值