11

是否可以在不更改按钮背景图像大小的情况下增加 UIButton 的可点击区域

我试过了:

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

&

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

但这些都不起作用。

请问有什么建议吗?

4

3 回答 3

14

制作 UIButton 类型buttonWithType:UIButtonTypeCustom并为其分配一个较小尺寸的图像。

不要将图像设置为背景图像,否则它会随按钮一起增长。改为将其设置为主图像。

例如,如果您想将可点击区域设置为 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)];

界面生成器:

界面生成器示例

于 2012-11-19T05:50:24.930 回答
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];
}
于 2012-11-06T07:56:07.827 回答
3

使用您喜欢的设计方法(界面生成器/视觉格式语言)与自动布局一起使用所需的大小布局 UIButton。将标题或图像设置为内容,并使用具有可点击区域大小的透明图像作为背景图像。

_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setImage:[UIImage imageNamed:@"contentImage"] forState:UIControlStateNormal];
[_button setBackgroundImage:[UIImage imageNamed:@"transparentImage"] forState:UIControlStateNormal];

这里是 _button.layer.borderWidth = 1 的示例。

例子

于 2015-09-02T13:14:23.277 回答