UIButton and setImage: not working consistently – inconsistent

I have a UIButton on a UIView. I want to programatically figure out which image to display inside the button when the view is displayed. I have overriden the drawRect method in the UIView and used a setImage to display the desired image. However, when the view displays, sometimes it draws the desired image, and sometimes it does not. I have to touch anywhere in the view for the image to show up in the button. Please help !

Here is the drawRect method for the view.

- (void)drawRect:(CGRect)rect
{
[myButton setImage:[UIImage imageNamed:@"myImage.png"] forState:UIControlStateNormal];
}

Everything is wired up IB correctly. I don’t understand why the image appears/doesn’t appear consistently. Thanks very much.

Answer

You really don’t want to override drawRect.

The proper thing to do is implement a UIViewController, and override viewWillAppear:.

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.myButton setImage:[UIImage imageNamed:@"myImage.png"] forState:UIControlStateNormal];
};