iOS干货

iOS中xib加载xib问题

2019-02-21  本文已影响0人  张qiaoyi

由于业务中有重复的view所以我打算抽出来复用,为了简便我用了xib(B),然后直接在xib(A)中使用B。运行发现空白一片。断点发现B初始化了,但是B里面的资源没有初始化。

几番度娘终于解决:

 需要在B中的.m文件中重写 initWithCode:(NSCoder*)aDecoder 方法,本意上A加载B无法直接加载到B的xib资源,所以我们在归档的方法中手动的去加载这个资源,

"一般对于这种需求,我们会选择在 init(coder:) 中加载目标 nib 然后将它作为 subview 添加到目标 view 中。"

那么重点来了, 很多人提到说在归档方法中会死循环,确实在loadnib方法中也会调用到归档方法, 所以这里要特别注意一下, 在B的xib文件中,关联头文件很重要, 只需在File's Owner 关联类, 而在view上是不需要关联的,所以这个xib有什么属性也是在File's Owner 上来关联。

xib(B)

@interface SPTNWSContentLabelView()

@property (nonatomic, strong) SPTNWSContentLabelView *customView;

@property (nonatomic, weak) IBOutlet UILabel*showLabel;  //标签

@property (nonatomic, weak) IBOutlet UILabel *authorNameLabel; //作者

@property(weak,nonatomic)IBOutletNSLayoutConstraint*authorNameLabelLeading;

@property (nonatomic, weak) IBOutlet NSLayoutConstraint *timeLabelLeading;

@end

@implementationSPTNWSContentLabelView

- (instancetype)initWithCoder:(NSCoder*)aDecoder {

    if(self= [superinitWithCoder:aDecoder]) {

        _customView = [[SPTNWSCommonHelper newsBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil].firstObject;

        [self addSubview:_customView];

        _customView.sn_insets(UIEdgeInsetsZero).sn_layout();

    }

    return self;

}

重点:

1、必须要用 loadNibNamed:方法加载一个_customView,然后作为子view添加到self上。这样该xib的子视图就都能初始化并显示。

2、必须要设置_customView的frame

参考帖子:https://blog.csdn.net/sinat_35927740/article/details/79940415

上一篇下一篇

猜你喜欢

热点阅读