要制作一个如下图所示的APP界面,大多数是以九格宫的形式展示应用信息.
搭建九格宫的步骤一般为:
1.明确每一块用得是什么view
2.明确每个view之间的父子关系
3.添加各个格子view
4.加载app数据
5.添加格子内部的子控件
6.给给子内部的子控件装配数据
具体计算每个格子在UIView中的位置,计算方法如下:
如上图,每一列的x值一样,由列号决定x值;每一行的y值一样,行号决定y值.
例:
第一行每个格子的x值为: 第一个间隙marginX + 前面格子的列数 * (间隙marginX + 格子的宽度)
第一行每个格子的y值为: 第一个间隙marginY + 前面格子的行数 * (间隙marginY + 格子的高度)
设每行的格子数为:count,当前为第n个格子,则:前面格子的列数为
n % count; 前面格子的行数为 n / count.
相关代码如下:
- (NSMutableArray *)appsArray {
if (nil == _appsArray) {
NSMutableArray *appArray = [[NSMutableArray alloc] init];
// 获取plist全路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil];
// 取出字典数组
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
for (NSDictionary *dict in dictArray) {
App *app = [App appWithDict:dict];
[appArray addObject:app];
}
_appsArray = appArray;
}
return _appsArray;
}
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat appW = 85;
CGFloat appH = 140;
// 总列数
int totalColumns = 3;
// 间隙
CGFloat marginX = (self.view.frame.size.width - totalColumns * appW) / (totalColumns + 1);
CGFloat marginY = 15;
for (int i = 0; i < self.appsArray.count; i++) {
App *app = self.appsArray[i];
// 创建小框框
UIView *appView = [[UIView alloc] init];
// 计算行号和列号
int row = i / totalColumns;
int col = i % totalColumns;
CGFloat appX = marginX + col * (marginX + appW);
CGFloat appY = 30 + row * (marginY + appH);
appView.frame = CGRectMake(appX, appY, appW, appH);
[self.view addSubview:appView];
// 添加图片
UIImageView *iconView = [[UIImageView alloc] init];
CGFloat iconW = 65;
CGFloat iconH = 65;
CGFloat iconX = (appView.frame.size.width - iconW) / 2;
CGFloat iconY = 0;
iconView.frame = CGRectMake(iconX, iconY, iconW, iconH);
iconView.image = [UIImage imageNamed:app.icon];
[appView addSubview: iconView];
// 添加名字
UILabel *nameLavel = [[UILabel alloc] init];
CGFloat nameX = 0;
CGFloat nameY = iconH + 10;
CGFloat nameW = appW;
CGFloat nameH = 25;
nameLavel.text = app.name;
nameLavel.textAlignment = 1;
nameLavel.font = [UIFont systemFontOfSize:14];
nameLavel.frame = CGRectMake(nameX, nameY, nameW, nameH);
[appView addSubview:nameLavel];
// 添加按钮
UIButton *iconBtn = [[UIButton alloc] init];
CGFloat btnX = 10;
CGFloat btnY = nameY + nameH + 10;
CGFloat btnW = appW - 2 * btnX;
CGFloat btnH = 25;
iconBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
// 设置btn图片背景
[iconBtn setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal];
// 设置btn高亮背景
[iconBtn setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted];
// 添加文字
[iconBtn setTitle:@"下载" forState:UIControlStateNormal];
iconBtn.titleLabel.font = [UIFont systemFontOfSize:15];
[appView addSubview:iconBtn];
}
}