简体   繁体   中英

How do I call a custom init on a view controller instantiated from a Storyboard scene in interface builder?

If I am using interface builder to manage storyboards for my app, how can I call a custom init selector when view / view controller instances are created?

For example if I have a view controller in a Storyboard scene, and its Custom Class is a UIViewController subclass, with a custom initialiser, such as initWithMediaType: , which takes an NSUInteger as an argument, how can I specify in Interface Builder that initWithMediaType: should be called, passing in a given argument?

When you init your UIViewController from storyboard The system actually calls - (instancetype)initWithCoder:(NSCoder *)coder .

So, When you want to make your own init, you should override - (instancetype)initWithCoder:(NSCoder *)coder method in your custom UIViewController .

For your specific question, you can consider use prepareForSegue: and set your mediaType in it:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"YOUR_SEGUE_NAME_HERE"])
    {
        // Get reference to the destination view controller
        YourViewController *vc = [segue destinationViewController];

        // Pass any objects to the view controller here, like...
        [vc setMyObjectHere:object];
    }
}

Hope that help.

If you want to specify in Interface Builder, declare mediaType as a property in your UIViewController subclass, and use 'User Defined Runtime Attributes'.

屏幕截图

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