iOS开发中 xib模块化设计

前言

目标就是方便的将xib写的视图 方便的封装成一个组件来用

代码及使用方式

OC代码

ZJXibView.h

1
2
3
4
5
#import <UIKit/UIKit.h>

@interface ZJXibView : UIView
@property(strong,nonatomic)UIView *contentView;
@end

ZJXibView.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#import <Foundation/Foundation.h>
#import "ZJXibView.h"

@implementation ZJXibView

-(instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
[self loadView];
return self;
}
-(void)awakeFromNib{
[super awakeFromNib];
[self loadView];
}

-(void)layoutSubviews{
[super layoutSubviews];
self.contentView.frame = self.bounds;
}

-(void)loadView{
if(self.contentView){
return;
}

NSString* clazzName = NSStringFromClass(self.classForCoder);
NSArray* nameArray =[clazzName componentsSeparatedByString:@"."];
NSString * xibName =nameArray[0];
if(nameArray.count == 2){
xibName = nameArray[1];
}
self.contentView = [[NSBundle mainBundle]loadNibNamed:xibName owner:self options:nil].firstObject;
[self addSubview:self.contentView];
}

@end

Swift3代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import UIKit

@objc class ZJXibView: UIView {

@IBOutlet var contentView: UIView!


override init(frame: CGRect) {
super.init(frame: frame)
self.loadView()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}


override func awakeFromNib() {
super.awakeFromNib()
self.loadView()

}

override func layoutSubviews() {
super.layoutSubviews()
self.contentView.frame = self.bounds
}

fileprivate func getXibName() -> String {
let clzzName = NSStringFromClass(self.classForCoder)
let nameArray = clzzName.components(separatedBy: ".")
var xibName = nameArray[0]
if nameArray.count == 2 {
xibName = nameArray[1]
}
return xibName
}


func loadView() {
if self.contentView != nil {
return
}
let nibs = Bundle.main.loadNibNamed(getXibName(), owner: self, options: nil)
self.contentView = nibs![0] as! UIView
self.contentView.frame = self.bounds
self.contentView.backgroundColor = UIColor.clear
self.addSubview(self.contentView)
}
}

使用方法

比如我们的xib名字为ZJUserPicView.xib
就必须建一个相同名字的类ZJUserPicView.swift并继承ZJXibView

ZJUserPicView.swift

1
2
3
4
5
6
7
8
9
10
11
12
import UIKit

class ZJUserPicView: ZJXibView {

@IBOutlet weak var picImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!

override func awakeFromNib() {
super.awakeFromNib()
}

}

ZJUserPicView.xibFile's Owner的Class指定为ZJUserPicView.swift
然后连接picImageViewnameLabel

这样ZJUserPicView就可以整体做一个组件来用了

完整示例