- UIButton的響應區域應當不小于44x44pt
方法一
- 繼承UIButton,覆寫Button的方法
- 代碼如下:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if (!self.userInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
return nil;
}
CGRect touchuRect = CGRectInset(self.bounds, -44 , -44);
if (CGRectContainsPoint(touchuRect, point)) {
for (UIView *subView in [self.subviews reverseObjectEnumerator]) {
CGPoint convertedPoint = [subView convertPoint:point toView:self];
UIView *hinTestView = [subView hitTest:convertedPoint withEvent:event];
if (hinTestView) {
return hinTestView;
}
}
return self;
}
return nil;
}
方法二
- 也是繼承UIButton,覆寫Button的方法
- 代碼如下:
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
CGRect bounds = self.bounds;
//若原熱區小于44x44,則放大熱區,否則保持原大小不變
CGFloat widthDelta = MAX(44.0 - bounds.size.width, 0);
CGFloat heightDelta = MAX(44.0 - bounds.size.height, 0);
bounds = CGRectInset(bounds, -0.5 * widthDelta, -0.5 * heightDelta);
return CGRectContainsPoint(bounds, point);
}
點擊測試,代碼如下:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
// 方法一的按鈕
LXKButton *redButton = [[LXKButton alloc] initWithFrame:CGRectMake(100, 100, 2, 2)];
redButton.backgroundColor = [UIColor redColor];
[redButton addTarget:self action:@selector(redButtonClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:redButton];
// 方法二的按鈕
LXKButton2 *blackButton = [[LXKButton2 alloc] initWithFrame:CGRectMake(100, 300, 2, 2)];
blackButton.backgroundColor = [UIColor blackColor];
[blackButton addTarget:self action:@selector(blackButtonClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:blackButton];
}
- (void)redButtonClicked {
NSLog(@"點擊紅色按鈕");
}
- (void)blackButtonClicked {
NSLog(@"點擊黑色按鈕");
}
- 寫成category好嗎?感覺都所有的button都被擴大的方法,而且不經過自己調用就實現不太好
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。