如何在不增加背景图像大小的情况下增加(自定义类型)UIButton的可拍摄(击打)区域

时间:2012-11-06 07:36:26

标签: ios ios5 uibutton

是否可以在不改变Button背景图像大小的情况下增加UIButton的可拍摄区域

我试过了:

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

&安培;

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

但这些都没有奏效。

有什么建议吗?

3 个答案:

答案 0 :(得分: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)];

Interface Builder:

Interface Builder example

答案 1 :(得分: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];
}

答案 2 :(得分: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的示例。

Example http://i59.tinypic.com/wwnt5u.png