xib的封装
为了代码实用性高,每次用到xib的时候,最好都要进行封装;
使用xib封装一个自定义view的步骤:
1:新建一个继承自UIView的自定义View,假设类名叫(WYAppView)
2: 新建一个WYAppView.xib文件来描述WYAppview 的内部结构(最好设置成跟类名一样)
3:修改UIView的类型为WYAppView 真实类型 (就是继承自我们的自定义View)
4:将内部的子控件跟WYAppView 进行连线
5:WYAppView提供一个模型属性
6:再封装方法中 重写模型属性的set方法,因为在set方法中可以拿到外界传递的模型数据
7:把模型数据拆开,分别设置数据到对应的子控件中
8:补充:提供一个创建MJAppView 的类方法,将读取xib的代码屏蔽起来(返回一个模型)
代码示例:
1:xib图例
2:封装类WYAppView.h文件
#import <UIKit/UIKit.h>
#import "appModel.h"
@interface WYAppView : UIView
@property(nonatomic,strong)appModel *app;
+(instancetype)appWithView;
/** 初始化一个appView ,并且把传递过来的模型数据 传给我们的自定义模型属性(相当于初始化view和传递模型写到一个方法里面了)*/
+(instancetype)appWithViewWithApp:(appModel *)apModel;
@end
3:封装类WYAppView.m文件
#import "WYAppView.h"
@interface WYAppView ()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *nameLable;
@end
@implementation WYAppView
//重写模型的set方法
-(void)setApp:(appModel *)app
{
_app = app;
self.iconView.image = [UIImage imageNamed:app.icon];
self.nameLable.text = app.name;
}
//两种书写方式,这里是先写的appWithView 方法
//+(instancetype)appWithView
//{
// NSBundle *bundal = [NSBundle mainBundle];
// NSArray *objs = [bundal loadNibNamed:@"WYAppView" owner:nil options:nil];
// return [objs lastObject];
//}
//+(instancetype)appWithViewWithApp:(appModel *)apModel
//{
// WYAppView *pView = [self appWithView];
// pView.app = apModel;
// return pView;
//}
//这里是先写的appWithViewWithApp:方法
+(instancetype)appWithViewWithApp:(appModel *)apModel
{
NSBundle *bundal = [NSBundle mainBundle];
NSArray *objs = [bundal loadNibNamed:@"WYAppView" owner:nil options:nil];
WYAppView *pv = [objs lastObject];
pv.app = apModel;
return pv;
}
+(instancetype)appWithView
{
return [self appWithViewWithApp:nil];
}
@end