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.
It sounds like you are using
viewDidLoad:correctly. According to Apple’s docs:If your goal is to encapsulate this functionality at the
UIViewlevel, trylayoutSubviews.