如何扩展UIButton的hitTest区域而不挤出它的背景图像?

Tab*_*Tab 4 iphone objective-c uibutton ios

我已经设置了UIButton背景图像并在其上添加了标题(我setBackgroundImage没有使用方法setImage).现在我想扩展a的hitTest区域UIButton而不挤出它的背景图像.

我怎样才能做到这一点?

Rud*_*vič 5

这是已接受答案的更正版本.我们正在使用bounds,而不是frameCGRectInset代替CGRectMake.更清洁,更可靠.

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    return CGRectContainsPoint([self expandedBounds], point) ? self : nil;
}

- (CGRect)expandedBounds {
    return CGRectInset(self.bounds, -20, -20);
}
Run Code Online (Sandbox Code Playgroud)


joe*_*l.d 5

更简洁的方法是覆盖pointInside.

这是一个Swift版本:

override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
    let expandedBounds = CGRectInset(self.bounds, -15, -15)
    return CGRectContainsPoint(expandedBounds, point)
}
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记检查你的视图是否可见并且有一个窗口,否则你可能会得到有趣的结果...... (3认同)
  • @steipete 希望你的评论早点发表……结果不是那么有趣! (2认同)

Nen*_*d M 1

好吧,你可以扩展 UIButton 并重写 UIView 的 hitTest 方法:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    int expandMargin = 20;
    CGRect extendedFrame = CGRectMake(0 - expandMargin , 0 - expandMargin , self.bounds.size.width + (expandMargin * 2) , self.bounds.size.height + (expandMargin * 2));
    return (CGRectContainsPoint(extendedFrame , point) == 1) ? self : nil;
}
Run Code Online (Sandbox Code Playgroud)