如何在不增加背景图像大小的情况下增加(自定义types)UIButton的可打(打)区域
是否可以增加UIButton的可打印区域而不改变Button的背景图像的大小
我试过了:
[shareButton setContentEdgeInsets:UIEdgeInsetsMake(top, left, bottom, right)];
&
[shareButton setImageEdgeInsets:UIEdgeInsetsMake(top, left, bottom, right)];
但没有一个工作。
有什么build议吗?
创buildtypes为buttonWithType:UIButtonTypeCustom
的UIButton buttonWithType:UIButtonTypeCustom
并为其分配较小尺寸的图像。
不要将图像设置为背景图像,或者随着button的增长。 将其设置为主图像。
例如,如果要将可打印区域设置为64×64大小,并且要显示大小为32×32的图像,则button大小应为64×64,图像大小应为32×32。
编程方式:
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)];
界面生成器:
inheritanceUIButton的superview,重写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]; }
使用你喜欢的devise方法(界面生成器/视觉格式语言)和Autolayout一起,然后用所需的尺寸布置UIButton。 将标题或图像设置为内容,并使用可打字区域大小的透明图像作为背景图像。
_button = [UIButton buttonWithType:UIButtonTypeCustom]; [_button setImage:[UIImage imageNamed:@"contentImage"] forState:UIControlStateNormal]; [_button setBackgroundImage:[UIImage imageNamed:@"transparentImage"] forState:UIControlStateNormal];
这里有一个_button.layer.borderWidth = 1的例子。