Xib 九宫格应用管理
使用xib封装一个自定义view的步骤
1> 新建一个继承UIView的自定义view,假设类名叫做(AppView)
2> 新建一个AppView.xib文件来描述MJAppView内部的结构
3> 修改UIView的类型为MJAppView真是类型
4> 将内部的子控件跟MJAppView进行属性连线
5> AppView提供一个模型属性
6> 重写模型属性的set方法,因为在set方法中可以拿到外界传递的模型数据
7> 把模型数据拆开,分别设置数据到对应的子控件中
8> 补充:提供一个创建MJAppView的类方法,将读取xib文件的代码屏蔽起来
#import "ViewController.h"
#import "MyApp.h"
#import "MyAppView.h"
@interface ViewController ()
@property(nonatomic,strong)NSArray* apps;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
int totalColumns=3;
CGFloat appW=85;
CGFloat appH=90;
CGFloat marginX=(self.view.frame.size.width-totalColumns*appW)/(totalColumns+1);
CGFloat marginY=15;
for (int index=0; index<self.apps.count; index++) {
MyAppView *appView = [MyAppView appViewWithApp:self.apps[index]];
[self.view addSubview:appView];
int row = index / totalColumns;
int col = index % totalColumns;
CGFloat appX = marginX + col * (appW + marginX);
CGFloat appY = 30 + row * (appH + marginY);
appView.frame = CGRectMake(appX, appY, appW, appH);
}
}
- (NSArray*)apps
{
if (_apps==nil) {
NSString* path=[[NSBundle mainBundle]pathForResource:@"app.plist" ofType:nil];
NSArray* dictArray=[NSArray arrayWithContentsOfFile:path];
NSMutableArray* appArray=[NSMutableArray array];
for (NSDictionary* dict in dictArray) {
MyApp* app=[MyApp appWithDict:dict];
[appArray addObject:app];
}
_apps=appArray;
}
return _apps;
}
@end
#import
@class MyApp;
@interface MyAppView : UIView
/**
* 数据模型
*/
@property(nonatomic,strong)MyApp* app;
+(instancetype)appView;
/**
* 通过模型数据来创建一个view
*/
+ (instancetype)appViewWithApp:(MyApp*)app;
@end
#import "MyAppView.h"
#import "MyApp.h"
@interface MyAppView ()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@end
@implementation MyAppView
+ (instancetype)appViewWithApp:(MyApp *)app
{
NSBundle* bundle=[NSBundle mainBundle];
NSArray* objs=[bundle loadNibNamed:@"MyAppView" owner:nil options:nil];
MyAppView* appView=[objs lastObject];
appView.app=app;
return appView;
}
+ (instancetype)appView
{
return [self appViewWithApp:nil];
}
- (void)setApp:(MyApp *)app
{
_app=app;
self.iconView.image=[UIImage imageNamed:app.icon];
self.nameLabel.text=app.name;
}
@end
Xib
Model
@interface MyApp : NSObject
/**
* 名称
*/
@property(nonatomic,copy)NSString* name;
/**
* 图标
*/
@property(nonatomic,copy)NSString* icon;
/**
* 通过字典来初始化模型对象
* @param dict 字典对象
* @return 已经初始化完毕的模型对象
*/
- (instancetype)initWithDict:(NSDictionary*)dict;
+ (instancetype)appWithDict:(NSDictionary*)dict;
@end
@implementation MyApp
- (instancetype)initWithDict:(NSDictionary*)dict
{
if (self=[super init]) {
self.name=dict[@"name"];
self.icon=dict[@"icon"];
}
return self;
}
+ (instancetype)appWithDict:(NSDictionary*)dict;
{
return [[self alloc]initWithDict:dict];
}
@end
实例图