#import "ViewController.h"
#import "HMApp.h"
#import "HMAppView.h"
@interface ViewController ()
@property (nonatomic, strong) NSArray *apps;
@end
@implementation ViewController
#pragma mark - 懒加载apps中的数据
//- (NSArray *)apps {
// if (_apps == nil) {
// // 加载数据
// // 1. 获取plist文件的路径
// NSString *path = [[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil];
//
// // 2. 根据给定的路径, 加载plist文件
// // 这个方法返回的是一个装满了字典的数组
// NSArray *arrayDicts = [NSArray arrayWithContentsOfFile:path];
//
//
// // 3. 创建一个用来存放模型的数组
// NSMutableArray *arrayM = [NSMutableArray array];
//
// // 4. 字典转模型
// for (NSDictionary *dict in arrayDicts) {
// // 根据字典, 创建一个模型
// HMApp *model = [HMApp appWithDict:dict];
// // 把模型添加到数组中
// [arrayM addObject:model];
// }
//
// _apps = arrayM;
// }
// return _apps;
//}
- (NSArray *)apps {
if (_apps == nil) {
_apps = [HMApp allApp];
}
return _apps;
}
#pragma mark - 其他方法
- (void)viewDidLoad {
[super viewDidLoad];
// NSLog(@"%@", [NSBundle mainBundle].bundlePath);
// 计算九宫格坐标的代码
// 假设一行有3个
int columns = 3;
// 设置每个appView的frame
// 假设每个view的宽度和高度一定
CGFloat appW = 75;
CGFloat appH = 90;
// 计算边距(间隔)
// 计算屏幕的宽度
CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
CGFloat marginTop = 30;
// 水平方向的间距
CGFloat marginX = (screenW - appW * columns) / (columns + 1);
// 1. 根据self.apps中的数据创建对应的UIView, 并显示到界面上
for (int i = 0; i < self.apps.count; i++) {
// 获取每个应用的数据
HMApp *model = self.apps[i];
// 封装, 就是封装变化。
// 通过加载xib文件来创建对应的UIView
HMAppView *appView = [HMAppView appView];
// 原始方式
// HMAppView *appView = [[[NSBundle mainBundle] loadNibNamed:@"HMAppView" owner:nil options:nil] lastObject];
// appView.imgViewIcon.image = [UIImage imageNamed:app.icon];
// appView.lblName.text = app.name;
// 把模型数据赋值给自定义View
appView.app = model;
// 计算每个appView所在的列的索引
int col_idx = i % columns;
// 计算每个appView所在的行索引
int row_idx = i / columns;
// 计算每个appView的x和y
CGFloat appX = marginX + col_idx * (appW + marginX);
CGFloat appY = marginTop + row_idx * (appH + marginTop);
appView.frame = CGRectMake(appX, appY, appW, appH);
// 把appView添加到界面上
[self.view addSubview:appView];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end