Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my IBDesignable allow me to use setImage: on my custom UIButton?

In layoutSubviews I'm calling setImage() and pass it a UIImage but it never shows up in Interface Builder, but it always shows up when I run the program.

like image 293
Doug Smith Avatar asked Oct 27 '14 19:10

Doug Smith


2 Answers

Probably you are loading your UIImage with this method:

UIImage *image = [UIImage imageNamed:@"image"];

This does not work in interface builder because imageNamed: method uses main bundle but IB loads resources in different way. Try something like this:

- (void)prepareForInterfaceBuilder
{
    UIImage *image = [UIImage imageNamed:@"image" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil];
    [self setImage:image forState:UIControlStateNormal];
}
like image 97
Leszek Szary Avatar answered Sep 24 '22 03:09

Leszek Szary


Going to give the swift answer for anyone who comes across this problem like I did.

The problem is that paths to images are different in Interface Builder than they are in your app.

 let bundle = Bundle(for: self.classForCoder)
 image = UIImage(named: "your_image.png", in: bundle, compatibleWith: self.traitCollection)!
 self.setImage(image, for: .normal) 
like image 39
A. Maly Avatar answered Sep 21 '22 03:09

A. Maly