How to embed a custom view xib in a storyboard scene?

前端 未结 11 551
生来不讨喜
生来不讨喜 2021-01-29 21:33

I\'m relatively new in the XCode/iOS world; I\'ve done some decent sized storyboard based apps, but I didn\'t ever cut me teeth on the whole nib/xib thing. I want to use the sam

11条回答
  •  借酒劲吻你
    2021-01-29 21:59

    I've been using this code snippet for years. If you plan on having custom class views in your XIB just drop this in the .m file of your custom class.

    As a side effect it results in awakeFromNib being called so you can leave all your init/setup code in there.

    - (id)awakeAfterUsingCoder:(NSCoder*)aDecoder {
        if ([[self subviews] count] == 0) {
            UIView *view = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil][0];
            view.frame = self.frame;
            view.autoresizingMask = self.autoresizingMask;
            view.alpha = self.alpha;
            view.translatesAutoresizingMaskIntoConstraints = self.translatesAutoresizingMaskIntoConstraints;
            return view;
        }
        return self;
    }
    

提交回复
热议问题