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

2

8

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.

Sheldonshelduck answered 27/10, 2014 at 19:22 Comment(0)
S
15

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];
}
Skysail answered 28/11, 2014 at 6:52 Comment(0)
A
5

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) 
Apteral answered 4/7, 2017 at 0:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.