Wednesday, May 02, 2012

Set Image Programmatically

In my iOS project, I have a button. I want to add image to its view in codes. The reason I want to do it is that I have another class with API to provide image. The class uses database entity. If the entity contains a property of imagePath, the image will be loaded from the path; otherwise, the image will be from the app as default image.

I tried to use the following codes to load the image:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.imageButton.imageView.image =
      [MyImageManager imageForEntity:self.entity]
}

The above codes do not set image at all. I checked my image and there are loaded from my API.

After googling for a while, I found the reason. There is setImage message for button's image with additional parameters. I have to explicitly call this message to set image.  Here is my updated codes:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.imageButton setImage:
      [MyImageManager imageForEntity:self.entity]
                            forState:UIControlStateNormal];
}

There are more states available to set images for a button:

enum {
    UIControlStateNormal       = 0,
    // used when UIControl isHighlighted is set
    UIControlStateHighlighted  = 1 << 0,
    UIControlStateDisabled     = 1 << 1,
    // flag usable by app (see below)
    UIControlStateSelected     = 1 << 2,
    // additional flags available for application use
    UIControlStateApplication  = 0x00FF0000,
    // flags reserved for internal framework use
    UIControlStateReserved     = 0xFF000000
};
typedef NSUInteger UIControlState;

0 comments: