IOS中使用.xib文件封装一个自定义View
1.新建一个继承UIView的自定义view,假设类名叫做 MyAppVew
#import <UIKit/UIKit.h> @class MyApp; @interface MyAppView : UIView @property(strong,nonatomic) MyApp*app; +(instancetype)appView; @end
MyAppView.h
#import "MyAppView.h" #import "MyApp.h" @interface MyAppView () @property (weak, nonatomic) IBOutlet UIImageView *iconView; @property (weak,nonatomic) IBOutlet UILabel *nameLable; @end @implementation MyAppView -(void)setApp:(MyApp *) app { _app=app; self.iconView.image=[UIImage imageNamed:app.icon]; self.nameLable.text=app.name; //NSLog(@"%@", app.icon); } +(instancetype) appView{ NSBundle *bundle=[NSBundle mainBundle]; NSArray *objs=[bundle loadNibNamed:@"AppInfoView" owner:nil options:nil]; return [objs lastObject]; } +(instancetype) appViewWithApp:(MyApp *)app{ MyAppView *appView=[self appView]; appView.app=app; return appView; } @end
2.新建一个MyAppVIew.xib文件来描述MyAppView内部结构
3.修改UIView的类型为MyAppView类型
4.将内部的子控件跟MyAppView进行属性连线
5.MyAppView提供一个模型属性
@interface MyAppView ()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak,nonatomic) IBOutlet UILabel *nameLable;
6.重写模型属性的set方法,因为set方法中可以拿到外界传递的模型数据
-(void)setApp:(MyApp *) app { _app=app; self.iconView.image=[UIImage imageNamed:app.icon]; self.nameLable.text=app.name; //NSLog(@"%@", app.icon); }
7.把模型数据拆开,分别设置数据到对应的子控件中
8.补充:提供一个创建MyAppView的类方法,将读取的.xib文件的代码屏蔽起来
+(instancetype) appView{ NSBundle *bundle=[NSBundle mainBundle]; NSArray *objs=[bundle loadNibNamed:@"AppInfoView" owner:nil options:nil]; return [objs lastObject]; } +(instancetype) appViewWithApp:(MyApp *)app{ MyAppView *appView=[self appView]; appView.app=app; return appView; }
通过封装数据,对mvc有了初步认识。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。