Load view from an external xib file in storyboard

后端 未结 10 2266
一生所求
一生所求 2020-11-27 09:49

I want to use a view throughout multiple viewcontrollers in a storyboard. Thus, I thought about designing the view in an external xib so changes are reflected in every viewc

10条回答
  •  醉酒成梦
    2020-11-27 10:24

    This solution can be used even if your class does not have the same name as the XIB. For example, if you have a base view controller class controllerA which has a XIB name controllerA.xib and you subclassed this with controllerB and want to create an instance of controllerB in a storyboard, then you can:

    • create the view controller in the storyboard
    • set the class of the controller to the controllerB
    • delete the view of the controllerB in the storyboard
    • override load view in controllerA to:

    *

    - (void) loadView    
    {
            //according to the documentation, if a nibName was passed in initWithNibName or
            //this controller was created from a storyboard (and the controller has a view), then nibname will be set
            //else it will be nil
            if (self.nibName)
            {
                //a nib was specified, respect that
                [super loadView];
            }
            else
            {
                //if no nib name, first try a nib which would have the same name as the class
                //if that fails, force to load from the base class nib
                //this is convenient for including a subclass of this controller
                //in a storyboard
                NSString *className = NSStringFromClass([self class]);
                NSString *pathToNIB = [[NSBundle bundleForClass:[self class]] pathForResource: className ofType:@"nib"];
                UINib *nib ;
                if (pathToNIB)
                {
                    nib = [UINib nibWithNibName: className bundle: [NSBundle bundleForClass:[self class]]];
                }
                else
                {
                    //force to load from nib so that all subclass will have the correct xib
                    //this is convenient for including a subclass
                    //in a storyboard
                    nib = [UINib nibWithNibName: @"baseControllerXIB" bundle:[NSBundle bundleForClass:[self class]]];
                }
    
                self.view = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
           }
    }
    

提交回复
热议问题