Load view from an external xib file in storyboard

后端 未结 10 2268
一生所求
一生所求 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:41

    Assuming that you've created an xib that you want to use:

    1) Create a custom subclass of UIView (you can go to File -> New -> File... -> Cocoa Touch Class. Make sure "Subclass of:" is "UIView").

    2) Add a view that's based on the xib as a subview to this view at initialization.

    In Obj-C

    -(id)initWithCoder:(NSCoder *)aDecoder{
        if (self = [super initWithCoder:aDecoder]) {
            UIView *xibView = [[[NSBundle mainBundle] loadNibNamed:@"YourXIBFilename"
                                                                  owner:self
                                                                options:nil] objectAtIndex:0];
            xibView.frame = self.bounds;
            xibView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            [self addSubview: xibView];
        }
        return self;
    }
    

    In Swift 2

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let xibView = NSBundle.mainBundle().loadNibNamed("YourXIBFilename", owner: self, options: nil)[0] as! UIView
        xibView.frame = self.bounds
        xibView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        self.addSubview(xibView)
    }
    

    In Swift 3

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let xibView = Bundle.main.loadNibNamed("YourXIBFilename", owner: self, options: nil)!.first as! UIView
        xibView.frame = self.bounds
        xibView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.addSubview(xibView)
    }
    

    3) Wherever you want to use it in your storyboard, add a UIView as you normally would, select the newly added view, go to the Identity Inspector (the third icon on the upper right that looks like a rectangle with lines in it), and enter your subclass's name in as the "Class" under "Custom Class".

提交回复
热议问题