woshidan's loose leaf

ぼんやり勉強しています

ボタンのタッチ領域を広げる

iphone - How to expand the hitTest area of a UIButton without extruding it's background image? - Stack Overflow

CGRectInset - Core Graphics | Apple Developer Documentation

@implementation MyButton : UIButton

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    int expandedMargin = 10;
    CGRect expandedFrame = CGRectInset(self.bounds, - (expandedMargin * 2), - (expandedMargin * 2));
     // Insetの返り値で広がった長方形が欲しいときは値をマイナスに
    return (CGRectContainsPoint(expandedFrame , point) == 1) ? self : nil;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    MyButton* button = [[MyButton alloc] init];
    button.frame = CGRectMake(0, 0, 100, 100);
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button];
}

- (void)onClick:(UIView *)view {
    NSLog(@"clicked");
}