案例分析:
分析:
代码案例实现:
//
// ViewController.m
// 01-九宫格算法
//
// Created by FlyLee on 14-9-12.
// Copyright (c) 2014年 FLYLEE.CN. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
/*
数据容器
*/
@property (nonatomic,strong) NSArray *apps;
@end
@implementation ViewController
//懒加载
- (NSArray *)apps
{
if (_apps == nil) {
// 1.获得plist文件的全路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil];
// 2.加载数组
_apps = [NSArray arrayWithContentsOfFile:path];
}
return _apps;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//1. 每一行的列数
int totalCol = 3;
//2.每一个格子的尺寸及y值的常量
CGFloat appW = 85;
CGFloat appH = 90;
CGFloat startY = 30; //设置Y的初始位置,电池栏20 所以初始位置设置30
CGFloat marginY = 15; //设置Y的初始间隙空间
//3.间隙 = (控制器view的宽带 - 3 *格子的宽度 ) / 4;
CGFloat marginX = (self.view.frame.size.width - totalCol * appW) / (totalCol + 1);
int count = self.apps.count;
//4.根据应用管理的个数,创建格子
for (int i = 0 ; i < count; i++) {
//4.1 创建view
UIView *appView = [[UIView alloc] init];
appView.backgroundColor = [UIColor redColor];
//4.2 计算行号和列号
// i = 0, 1 ,2 / 3 = 0 初始的都是0行开始 0 , 1 , 2 ,3 ....
// i = 3, 4 ,5 / 3 = 1
int row = i / totalCol;
// i = 0 , 3, 6 % 3 = 0 初始的都是0列开始 0 , 1 , 2 ,3 ....
// i = 1, 4 , 7 %3 = 1
int col = i % totalCol;
// 4.3 计算x和y
CGFloat appX = marginX + (appW + marginX) * col;
CGFloat appY = startY + (appH + marginY) * row;
appView.frame = CGRectMake(appX,appY, appW,appH);
//4.4 添加格子到控制器的view
[self.view addSubview:appView];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end