有时候因为一些产品需求,显示的图片很小,但是点击的区域需要很大,我们可以通过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];