UIButton応答領域の拡大
2261 ワード
方法1
- (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;
}
方法2
- (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(@" ");
}