说明 | |
---|---|
首次发表 | 2017年06月02日 |
最近更新 | 2017年07月18日 |
通过复写pointInside: withEvent:
来实现需求,废话不多说,先上效果图,注意看鼠标点击的位置和控制台的打印(button没有image):
首先,我们自定义继承于UIButton
的CustomButton
:
CustomButton.h
#import <UIKit/UIKit.h>
@interface CustomeButton : UIButton
@end
再看CustomButton.m
里的代码:
#import "CustomeButton.h"
@implementation CustomeButton
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
CGRect bounds = self.bounds;
//我们想要button的相应宽度为size(60, 40)
CGFloat width = MAX(60 - bounds.size.width, 0);
CGFloat height = MAX(44 - bounds.size.height, 0);
//为什么要乘以 -0.5 呢?看 CGRectInset(CGRect rect, CGFloat dx, CGFloat dy) 的说明:
//its size adjusted by (2*dx,2*dy), relative to the source rectangle. If dx and dy are positive values, then the rectangle’s size is decreased.
//If dx and dy are negative values, the rectangle’s size is increased.
//注意:button的中心点不会改变
bounds = CGRectInset(bounds, -0.5 * width, -0.5 * height);
return CGRectContainsPoint(bounds, point);
}
@end
最后,就是在ViewController.m
里使用:
#import "ViewController.h"
#import "CustomeButton.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CustomeButton * button = [[CustomeButton alloc] initWithFrame:CGRectMake(100, 400, 22, 22)];
button.backgroundColor = [UIColor blueColor];
[button addTarget:self action:@selector(printH) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)printH {
NSLog(@"custom");
}
@end
推荐方法
当然,我会给你推荐一个更便捷的设置方法——分类。
UIButton+MZEnlargeTouchArea.h
@interface UIButton (MZEnlargeTouchArea)
/** 向四周增加的额外响应热区值 */
@property (nonatomic, assign) UIEdgeInsets mz_touchAreaInsets;
@end
UIButton+MZEnlargeTouchArea.m
@implementation UIButton (MZEnlargeTouchArea)
- (UIEdgeInsets)mz_touchAreaInsets {
return [objc_getAssociatedObject(self, @selector(mz_touchAreaInsets)) UIEdgeInsetsValue];
}
- (void)setMz_touchAreaInsets:(UIEdgeInsets)touchAreaInsets {
NSValue *value = [NSValue valueWithUIEdgeInsets:touchAreaInsets];
objc_setAssociatedObject(self, @selector(mz_touchAreaInsets), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
UIEdgeInsets touchAreaInsets = self.mz_touchAreaInsets;
CGRect bounds = self.bounds;
bounds = CGRectMake(bounds.origin.x - touchAreaInsets.left,
bounds.origin.y - touchAreaInsets.top,
bounds.size.width + touchAreaInsets.left + touchAreaInsets.right,
bounds.size.height + touchAreaInsets.top + touchAreaInsets.bottom);
return CGRectContainsPoint(bounds, point);
}
@end