Reuse a uiview xib in storyboard

前端 未结 7 2180
遇见更好的自我
遇见更好的自我 2020-11-29 15:19

I typically like to create and design my uiviews in interface builder. Sometimes I need to create a single view in a xib that can be reused in multiple view controllers in a

7条回答
  •  眼角桃花
    2020-11-29 15:48

    NEW! updated answer with ability to render directly in the storyboard (and swift!)

    Works in Xcode 6.3.1

    Create a new UIView named 'ReuseableView'

    • File > New > File > Source > Cocoa Touch Class > UIView

    Create a matching xib file named 'ReuseableView'

    • File > New > File > User Interface > View

    Set the file owner of the of the xib

    1. select the xib
    2. select file's owner
    3. set custom class to 'ReusableView' in the Identity Inspector. enter image description here

      • Note: Do not set the custom class of the view on the xib. Only the File Owner!

    Make an outlet from the view in the ReuseableView.xib to your ReuseableView.h interface

    1. Open Assistant Editor
    2. Control + Drag from the view to your interface

    enter image description here

    Add initWithCoder implementation to load view and add as a subview.

    - (id)initWithCoder:(NSCoder *)aDecoder{
        self = [super initWithCoder:aDecoder];
        if (self) {
    
            // 1. load the interface
            [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
            // 2. add as subview
            [self addSubview:self.view];
            // 3. allow for autolayout
            self.view.translatesAutoresizingMaskIntoConstraints = NO;
            // 4. add constraints to span entire view
            [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];
            [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];
    
        }
        return self;
    }
    

    enter image description here

    Test your reuseable view in a storyboard

    1. Open your storyboard
    2. Add a view
    3. Set that view's Custom Class

    enter image description here

    Run and observe! enter image description here

提交回复
热议问题