Question

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.

Was it helpful?

Solution

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];
};

OTHER TIPS

groundhog has the right answer, but I would just like to explain what is actually happening with your code, and why it works some of the time.

The drawRect method gets called every time the system wants your view object to display itself on the screen. Setting the button image in the drawRect method will change the button image, but since the system is already in the process of drawing to the screen, you will not actually see the change until the next time the views need to be redrawn. In this case, when you touch somewhere else in the view.

Thanks for the explanation. Unfortunately, this code is part of a larger project with another developer. I CAN'T change the current UIView to a UIViewController. Instead, I changed the button image in another fashion. I changed the button's state just prior to adding the UIView to the subview of the owning ViewController. ie: I issued the

[myButton setImage:[UIImage imageNamed:@"myImage.png"] forState:UIControlStateNormal];

Just prior to adding my UIView as a subView. ie:

[masterViewController.view addSubview:myView];

obviously, myButton is part of myView. Thanks for the assist.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top