Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set stretchableImageWithLeftCapWidth in Interface builder?

How do you set stretchableImageWithLeftCapWidth in Interface builder?

like image 256
erotsppa Avatar asked Apr 13 '10 20:04

erotsppa


2 Answers

Interface builder does not support stretchable images.

-(void) viewDidLoad {
  [super viewDidLoad];
  [myImageView setImage:[[myImageView image] stretchableImageWithLeftCapWidth:5 topCapHeight:5 ]];
}
like image 196
drawnonward Avatar answered Sep 21 '22 05:09

drawnonward


This is currently (as of version 4.5) a limitation of InterfaceBuilder. However, having to create an IBOutlet for each button and manually specify that the image is stretchable in viewDidLoad is not a great solution, if for no other reasons than it makes creating the UI more cumbersome and also more brittle.

Instead of that, let's create a UIButton subclass which will always make any background image stretchable by default. In this example I only stretch the normal and highlighted background image. For a production-ready class you would probably want to check all states of both background and foreground images and stretch them.

@implementation NTSTButton

- (id) initWithCoder:(NSCoder *)aDecoder {

    self = [super initWithCoder:aDecoder];
    if (self) {
        /* There is no support in IB for stretchable images. So, let's
           make sure _any_ background image assigned to this button 
           stretches correctly.
           Note: Setting the stretch cap to 10px, which should work with
           almost all button background images. 
        */
        UIImage *normalImage = 
                 [[self backgroundImageForState:UIControlStateNormal]
                        stretchableImageWithLeftCapWidth:10 topCapHeight:10] ;

        UIImage *highlightedImage = 
                 [[self backgroundImageForState:UIControlStateHighlighted]
                        stretchableImageWithLeftCapWidth:10 topCapHeight:10] ;

        [self setBackgroundImage:normalImage 
              forState:UIControlStateNormal];

        [self setBackgroundImage:highlightedImage 
              forState:UIControlStateHighlighted];
    }
    return self;
}

@end
like image 34
memmons Avatar answered Sep 20 '22 05:09

memmons