0
我有一個UIButton對象,我在其背景中使用可拉伸的圖像,所以我可以始終具有靈活的按鈕尺寸。UIButton - 只能在一個方向拉伸背景圖像?
事情是我想有一個固定的圖像高度(比如32px),但想要一個更高的可觸摸區域(蘋果UI準則總是說至少44px高)。
如果我在x中有一個可拉伸的圖像,那麼它不幸的也延伸到y中。我想告訴圖像不要在y上伸展。這可能嗎?
[編輯]是的。回答我的問題:
我有一個UIButton對象,我在其背景中使用可拉伸的圖像,所以我可以始終具有靈活的按鈕尺寸。UIButton - 只能在一個方向拉伸背景圖像?
事情是我想有一個固定的圖像高度(比如32px),但想要一個更高的可觸摸區域(蘋果UI準則總是說至少44px高)。
如果我在x中有一個可拉伸的圖像,那麼它不幸的也延伸到y中。我想告訴圖像不要在y上伸展。這可能嗎?
[編輯]是的。回答我的問題:
所以,只是爲了幫助別人,我可以回答我的問題:
@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
回答自己的問題的答案,而不是作爲對問題的編輯。你甚至可以這樣接受它。 – jrturton