#import "ViewController.h"
#import "CZapp.h" //引用模型类
@interface ViewController ()
@property (nonatomic ,strong) NSArray* apps; //声明数组保存数据
@end
@implementation ViewController
//懒加载
-(NSArray *)apps
{
if (_apps==nil) {
// 获取plist路径
NSString* path = [[NSBundle mainBundle] pathForResource:@"apps_plist" ofType:nil];
//根据数组得到数据
NSArray* arrayDict =[NSArray arrayWithContentsOfFile:path];
//声明一个可变数组用于保存数据
NSMutableArray * arrayModels =[NSMutableArray array];
//循环字典给模型赋值
for(NSDictionary * dict in arrayDict)
{
// 调用Czapp字典转模型
CZapp *model =[CZapp appWith:dict];
//模型赋值给可变数组
[arrayModels addObject:model];
}
}
return _apps;
}
- (void)viewDidLoad {
[super viewDidLoad];
/*
计算步骤:
1.确定每个app的宽和高
2.计算marginX,marginy,marginTop
3.计算每个app所在的行索引,列索引
4.根据当前app的行索引和列索引计算出appx和appy
*/
//定义变量为3列
int cloumns=3;
//获取View的宽度
CGFloat ViewWidth =self.view.frame.size.width;
CGFloat appW =75;
CGFloat appH =90;
//第一行距离顶部的距离
CGFloat marginTop =30;
CGFloat marginX = (ViewWidth- cloumns*appW)/(cloumns+1);
CGFloat marginY =marginX;//假设每行之间的间距和Marginx相等
//循环创建uiview
for (int i =0; i<12; i++)
{
//计算每个单元格所在列的索引
int colidx =i % cloumns;
//计算每个单元格所在行的索引
int rowidx = i /cloumns;
//创建UIView
UIView *appsView = [[UIView alloc]init];
//设置View背景色
appsView.backgroundColor =[UIColor blueColor];
CGFloat appX =marginX + colidx *(appW +marginX);
CGFloat appy =marginTop +rowidx *(appH +marginY);
appsView.frame =CGRectMake(appX, appy, appW, appH);
[self.view addSubview:appsView];
//创建uiImageView
UIImageView * imageIcon =[[UIImageView alloc]init];
imageIcon.backgroundColor =[UIColor greenColor];
CGFloat IconW =45;
CGFloat IconH =45;
CGFloat IconX =(appsView.frame.size.width -IconW)* 0.5;
CGFloat IconY =0;
imageIcon.frame = CGRectMake(IconX, IconY, IconW, IconH);
[appsView addSubview:imageIcon];
//创建lable
UILabel *lblName= [[UILabel alloc] init];
lblName.backgroundColor = [UIColor yellowColor];
CGFloat lblW = appsView.frame.size.width;
CGFloat lblh = 20;
CGFloat lblx =0;
CGFloat lbly =IconH;
lblName.frame =CGRectMake(lblx, lbly, lblW, lblh);
[appsView addSubview:lblName];
//创建 button
UIButton * btnDown =[[UIButton alloc]init];
btnDown.backgroundColor =[UIColor redColor];
CGFloat btnW =IconW;
CGFloat btnH =20;
CGFloat btnX =IconX;
//CGFloat btnY =lblY+lblh;
CGFloat btnY = CGRectGetMaxY(lblName.frame);
btnDown.frame =CGRectMake(btnX, btnY, btnW, btnH);
[appsView addSubview:btnDown];
}
}
@end
#import <Foundation/Foundation.h>
@interface CZapp : NSObject
@property (nonatomic,copy)NSString * name;
@property(nonatomic,copy) NSString* icon;// 声明属性
-(instancetype)initwithApp: (NSDictionary*)dict;
+(instancetype)appWith:(NSDictionary*)dict;
@end
//
// CZapp.m
// UIviewCode
#import "CZapp.h"
@implementation CZapp
// instancetype的作用,就是使那些非关联返回类型的方法返回所在类的类型
-(instancetype)initwithApp: (NSDictionary*)dict
{
if (self == [super init]) {
self.name=dict[@"name"];
self.icon=dict[@"icon"];
}
return self;
}
+(instancetype)appWith:(NSDictionary*)dict{
return [[self alloc] initwithApp:dict];
}
@end