简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM