UIButton - растягиваемое фоновое изображение только в одном направлении? - PullRequest
0 голосов
/ 21 ноября 2011

У меня есть объект UIButton, где я использую растягиваемое изображение для фона, поэтому у меня всегда могут быть гибкие размеры кнопок.

Дело в том, что я хотел бы иметь фиксированную высоту ИЗОБРАЖЕНИЯ (скажем, 32 пикселя), но хочу иметь более высокую сенсорную область (Apple UI Guidelines всегда должна иметь высоту не менее 44 пикселей).

Если у меня растягиваемое изображение в x, оно, к сожалению, растягивается и в y. Я хотел бы сказать, чтобы изображение не растягивалось у. Возможно ли это?

[РЕДАКТИРОВАТЬ] Да, это так. Отвечая на мой вопрос:

1 Ответ

3 голосов
/ 22 ноября 2011

Итак, чтобы помочь другим, я могу ответить на свой вопрос:

@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
...