利用runtime使按钮点击区域扩大

有时候因为一些产品需求,显示的图片很小,但是点击的区域需要很大,我们可以通过runtime来修改按钮的点击区域。

1、先创建一个UIButton的分类。

2、在通过runtime给分类添加属性。

@interface UIButton (ButtonExpansion)

// 输入需要扩大的数值
- (void)expandSize:(CGFloat)size;

@end
#import "UIButton+ButtonExpansion.h"
#import <objc/runtime.h>

@implementation UIButton (ButtonExpansion)

static char expandSizeKey;

    // 第一个参数:给哪个对象添加关联
    // 第二个参数:关联的key,通过这个key获取
    // 第三个参数:关联的value
    // 第四个参数:关联的策略
- (void)expandSize:(CGFloat)size{
    objc_setAssociatedObject(self, &expandSizeKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
}

// 获取设置的扩大size,来扩大button的rect
// 当前只是设置了一个扩大的size,当然也可以设置4个扩大的size,上下左右,具体扩大多少对应button的四个边传入对应的size
- (CGRect)expandRect{
// 根据关联的key,获取关联的值
    NSNumber *expandSize = objc_getAssociatedObject(self, &expandSizeKey);
    if (expandSize) {
        return CGRectMake(self.bounds.origin.x - expandSize.floatValue,
                          self.bounds.origin.y - expandSize.floatValue,
                          self.bounds.size.width + expandSize.floatValue + expandSize.floatValue,
                          self.bounds.size.height + expandSize.floatValue + expandSize.floatValue);
    }else{
        return self.bounds;
    }
}


- (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) ? YES : NO;
}

@end

 

    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    [btn setTitle:@"我是按钮" forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor redColor]];
    [btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    [btn expandSize:10];

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值