Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjusting UIView after loading from storyboard

I have a custom UIView class called MyView that I use together with a UIViewController configured through the storyboard. The majority of the view properties is configured through the Interface Builder; however, I need to adjust a couple of images programmatically before setting them as backgrounds for my button, like this:

-(void)setupVisuals {
    UIImage *image = [[UIImage imageNamed:@"myButton.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 10, 0, 10)];
    // _myButton is an IBOutlet property set through the storyboard:
    [_myButton setBackgroundImage:image forState:UIControlStateNormal];
}

The problem is that I cannot call [self setupVisuals] from the initializer*, because _myButton is nil at that time.

I solved the problem by adding this line to MyViewController's viewDidLoad:

[(MyView*)self.view setupVisuals];

With this call in place, everything works fine. However, this feels like a work-around, rather than a solution to what is likely a relatively common problem.

Is there a UIView method to override, or any other mechanism to complete the initialization of MyView's visuals without tapping into the viewDidLoad: mechanism?


* In this case, the initializer is initWithCoder: because the view is loaded from the storyboard. I verified that the initializer gets called correctly, but the visuals are not ready yet.
like image 882
Sergey Kalinichenko Avatar asked Nov 03 '22 09:11

Sergey Kalinichenko


1 Answers

It sounds like you are using viewDidLoad: correctly. According to Apple's docs:

You usually override this method to perform additional initialization on views that were loaded from nib files.

If your goal is to encapsulate this functionality at the UIView level, try layoutSubviews.

like image 61
pix0r Avatar answered Nov 11 '22 08:11

pix0r