gpt4 book ai didi

ios - UIButton - 只能在一个方向上拉伸(stretch)背景图像?

转载 作者:行者123 更新时间:2023-11-28 20:41:51 27 4
gpt4 key购买 nike

我有一个 UIButton 对象,我在其中使用可伸缩图像作为其背景,因此我始终可以拥有灵活的按钮大小。

问题是我想要一个固定的图像高度(比如 32px),但想要一个更高的可触摸区域(Apple UI Guidelines 总是说至少 44px 高)。

如果我在 x 轴上有一个可拉伸(stretch)的图像,不幸的是它也在 y 轴上拉伸(stretch)。我想告诉图像不要在 y 方向拉伸(stretch)。这可能吗?

[编辑] 是的。回答我自己的问题:

最佳答案

所以,为了帮助别人,我可以回答我自己的问题:

@interface StretchableXButton : UIButton
{
CGFloat imageHeight;
}
@property CGFloat imageHeight; // we need this later when we override an instance method

+ (id)buttonWithFrame:(CGRect)frame;

@end

现在是实现:

@implementation StretchableXButton
@synthesize imageHeight;

+ (id)buttonWithFrame:(CGRect)frame
{
StretchableXButton *button = [super buttonWithType:UIButtonTypeCustom];

UIImage *normalImage = [UIImage imageNamed: @"ButtonBGNormal.png" ];
UIImage *highlightedImage = [UIImage imageNamed:@"ButtonBGHighlighted.png" ];

button.frame = frame;
button.imageHeight = normalImage.size.height; // we need him later in the method below

// make the images stretchable
normalImage = [normalImage stretchableImageWithLeftCapWidth:normalImage.size.width/2 topCapHeight:normalImage.size.height/2];
highlightedImage = [highlightedImage stretchableImageWithLeftCapWidth:normalImage.size.width/2 topCapHeight:normalImage.size.height/2];

button.backgroundColor = [UIColor clearColor];

// SET OTHER BUTTON PROPERTIES HERE (textLabel, fonts, etc.)

[button setBackgroundImage:normalImage forState:UIControlStateNormal];
[button setBackgroundImage:highlightedImage forState:UIControlStateHighlighted];

return button;
}

// THIS IS THE TRICK. We make the height of the background rect match the image.
-(CGRect)backgroundRectForBounds:(CGRect)bounds
{
CGRect bgRect = bounds;
bgRect.origin.y = (bounds.size.height - imageHeight)/2.0f;
bgRect.size.height = imageHeight;

return bgRect;
}


@end

关于ios - UIButton - 只能在一个方向上拉伸(stretch)背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8210594/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com