UIButton and setImage: do not work in sequence - inconsistent

I have a UIButton on a UIView. I want to programmatically determine which image will be displayed inside the button when the view is displayed. I overridden the drawRect method in a UIView and used setImage to display the desired image. However, when a view is displayed, sometimes it draws the desired image, and sometimes not. I need to touch anywhere on the screen so that the image appears 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 correctly connected to IB. I do not understand why the image appears / does not appear sequentially. Many thanks.

+3
source share
3

drawRect.

- UIViewController viewWillAppear:.

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

groundhog , , , .

drawRect , , . drawRect , , , . , - .

+2

Thanks for the explanation. Unfortunately, this code is part of a larger project with another developer. I cannot change the current UIView to a UIViewController. Instead, I changed the button image in a different way. I changed the state of the button before adding the UIView to the subtitle of the own ViewController. i.e.: I released

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

Prior to adding my UIView as a subspecies. i.e:

[masterViewController.view addSubview:myView];

obviously myButton is part of myView. Thanks for the help.

+1
source

Source: https://habr.com/ru/post/1714175/


All Articles