参考文章地址: How do I create a custom iOS view class and instantiate multiple copies of it (in IB)?
#创建自己的xib.
我们创建一个xib文件以及和xib同名的类文件用于和xib文件进行关联.
选中 xib 文件中的 File’s Owner, 然后右边的 Class 添上我们创建的同名类文件: LRQCustomView
添加一些 view, 并在 LRQCustomView.h/m 中为这些 view 添加上属性引用或者事件.
一个按钮,一个label,并且添加了一个label属性 和 Button事件.
重写 - (instancetype)initWithCoder:(NSCoder *)aDecoder; 方法
#import "LRQCustomView.h"
@interface LRQCustomView()
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
@implementation LRQCustomView
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
UIView *view = [[[UINib nibWithNibName:@"LRQCustomView" bundle:[NSBundle mainBundle]]
instantiateWithOwner:self options:nil] lastObject];
[self addSubview:view];
return self;
}
- (IBAction)buttonAction:(id)sender {
NSLog(@"%s", __func__);
}
@end
然后进入 main.storyboard 里面, 添加两个view, 并且设置view的class为: LRQCustomView 即可.
运行效果:
Peace Out!