[UI向]在xib中使用另一个xib进行开发
文中类的命名没有严格按照驼峰法写,作者太饿了懒得改了……
--------------正文分割线-----------------
在使用xib进行界面搭建时,可能有一些xib文件是可以复用的,可能就需要在一个xib文件中使用另一个xib。
如下图所示。

这个步骤相对于用代码加载xib文件而言相对复杂一点,接下来一步一步讲解
1.创建两个xib
首先创建一个ParentViewController,创建时勾选同时创建Xib文件
再创建作为复用模块示例的ChildView类和对应的名为ChildView的xib文件


如下图,对ChildView的xib界面进行设置,通过设置Size为Free可以自View中添加一个Label和一个Button,并设置View的背景色。

2.关联xib文件与ChildView类
在ChildView.h中声明IBOutlet变量
@property(nonatomic,weak) IBOutlet UIView* view;
在ChildView.m中进行关联
#import "ChildView.h"
@implementation ChildView
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
[self creatView];
}
return self;
}
- (void)creatView{
[[NSBundle mainBundle] loadNibNamed:@"ChildView" owner:self options:nil];
[self addSubview:self.view];
self.view.frame = self.bounds; //填一下自动布局的坑!最好要写这一句
}
在ChildView.xib中,
- 1.点击左侧的File's Owner,设置他的类(此处为ChildView)
- 2.拉线设置IBOutlet

点击view 进行关联

这样我们就关联好了ChildView类和对应的xib文件。
3.在ParentView中添加控件
向ParentViewController.xib中添加一个UIView控件,该UIView的class属性设置为ChildView.即可关联到我们刚才设置好的可复用视图,设置一下布局约束,大功告成。

效果图

理一下思路,
实际上我们做的是创建了一个ChildView,在ChildView里加载了xib,并将这个xib中View的尺寸等于了ChildView的尺寸。
相当于将一个View贴在了ChildView上,这个View的子控件响应等都可以放在ChildView类里写。

欢迎评论区指正批评交流讨论!
小提醒
看到评论区的朋友们反馈发生错误,分析了一下可能是代码里的原因导致的,本文的方法到目前为止是没有问题的
如果遇到Crush报错*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x60400000bf70> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key view.'
看一下这里 http://blog.csdn.net/sunxiaoju/article/details/49936521
确认一下是不是你在修改xib和.m文件关联的时候忘记把旧约束删干净了,
如果还没有解决可以加我的QQ帮你看:125729996
感谢每一个阅读和喜欢。