How do you set stretchableImageWithLeftCapWidth in Interface builder?
Interface builder does not support stretchable images.
-(void) viewDidLoad {
[super viewDidLoad];
[myImageView setImage:[[myImageView image] stretchableImageWithLeftCapWidth:5 topCapHeight:5 ]];
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With