如何在不增加背景图像大小的情况下增加自定义类型UIButton的可点击区域?

11

如何在不改变按钮背景图大小的情况下增加UIButton的可点击区域?

我尝试过:

[shareButton setContentEdgeInsets:UIEdgeInsetsMake(top, left, bottom, right)];

&

[shareButton setImageEdgeInsets:UIEdgeInsetsMake(top, left, bottom, right)];

但是这些方法都没有起作用。

请问还有什么建议吗?

3个回答

14

创建一个类型为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)];

界面构建器:

示例


3

继承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];
}

除了子类化UIButton之外,是否有其他方法?有没有按钮的任何方法或属性可以手动设置点击区域? - W.S
3
那更糟糕了! - devios1
@crishoj 这不是真的,你可以子类化按钮并重写 pointInside 方法。 - pronebird
1
@Andy - 谢谢你的澄清。我已经删除了这条评论。 - crishoj

3

使用您喜欢的设计方法(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];

这是一个示例,其中_button.layer.borderWidth = 1。 示例

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接