如何在不改变按钮背景图大小的情况下增加UIButton的可点击区域?
我尝试过:
[shareButton setContentEdgeInsets:UIEdgeInsetsMake(top, left, bottom, right)];
&
[shareButton setImageEdgeInsets:UIEdgeInsetsMake(top, left, bottom, right)];
但是这些方法都没有起作用。
请问还有什么建议吗?
创建一个类型为buttonWithType:UIButtonTypeCustom
的UIButton并分配一个较小尺寸的图像。
不要将图像设置为背景图像,否则它会随着按钮一起增长。而应该将其设置为主要图像。
例如,如果您想将可点击区域设置为64x64大小,并想显示32x32大小的图像:按钮大小应为64x64,图像大小应为32x32。
以编程方式实现:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
// use an image with the desired size (for example 32x32)
[button setImage: [UIImage imageNamed: @"buttonIcon.png"] forState: UIControlStateNormal];
// just set the frame of the button (64x64)
[button setFrame: CGRectMake(xPositionOfMyButton, yPositionOfMyButton, 64, 64)];
界面构建器:
继承UIButton的父视图,重写hitTest:withEvent:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
CGPoint buttonPoint = [self convertPoint:point toView:_button];
if ([_button pointInside:buttonPoint withEvent:event]) { // you may add your requirement here
return _button;
}
return [super hitTest:point withEvent:event];
}
使用您喜欢的设计方法(Interface Builder / Visual Format Language),结合Autolayout布局所需大小的UIButton。将标题或图像设置为内容,并使用与可点击区域大小相同的透明图像作为背景图像。
_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setImage:[UIImage imageNamed:@"contentImage"] forState:UIControlStateNormal];
[_button setBackgroundImage:[UIImage imageNamed:@"transparentImage"] forState:UIControlStateNormal];