首页 > 代码库 > iOS开发UI篇章之应用管理的九宫格坐标计算
iOS开发UI篇章之应用管理的九宫格坐标计算
iOS开发UI篇—九宫格坐标计算
一、要求
完成下面的布局
二、分析
寻找左边的规律,每一个uiview的x坐标和y坐标。
三、实现思路
(1)明确每一块用得是什么view
(2)明确每个view之间的父子关系,每个视图都只有一个父视图,拥有很多的子视图。
(3)可以先尝试逐个的添加格子,最后考虑使用for循环,完成所有uiview的创建
(4)加载app数据,根据数据长度创建对应个数的格子
(5)添加格子内部的子控件
(6)给内部的子控件装配数据
四、代码示例
//
// TXViewController.m
// 屌丝逆天-应用管理01
//
// Created by 鑫 on 14-10-4.
// Copyright (c) 2014年 梁镋鑫. All rights reserved.
//
#import "TXViewController.h"
@interface TXViewController ()
/**
* 传放应用信息
*/
@property(nonatomic ,strong)NSArray *apps;
@end
@implementation TXViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//添加应用信息
//总列数(一行最多3列)
int totalColumns = 3;
//应用尺寸
CGFloat appW = 85;
CGFloat appH = 90;
//间隙 = (控制器view的宽度-3* 应用宽度)/4
CGFloat marginX = (self.view.frame.size.width - totalColumns * appW) / (totalColumns + 1);
CGFloat marginY = 15;
//根据应用个数创建对用框框
for (int index = 0; index < self.apps.count; index++) {
//3.1创建一个小框框
UIView *appView = [[UIView alloc]init];
//计算框框的位置
//计算行列号
int row = index / totalColumns;
int col = index % totalColumns;
//计算x和y
CGFloat appX = marginX + (appW + marginX)*col;
CGFloat appY = 30 + (appW + marginY) * row;
//设置frame
appView.frame = CGRectMake(appX, appY, appW, appH);
//添加框框到控制器的view中
[self.view addSubview:appView];
//创建内部小控件
//index对应的应用信息
NSDictionary *appInfo = self.apps[index];
//添加图片
UIImageView *iconView = [[UIImageView alloc] init];
//设置位置
CGFloat iconW = 45;
CGFloat iconH = 45;
CGFloat iconX = (appW - iconW) *0.5;
CGFloat iconY = 0;
iconView.frame = CGRectMake(iconX, iconY, iconW, iconH);
//设置图片
iconView.image = [UIImage imageNamed:appInfo[@"icon"]];
[appView addSubview:iconView];
//添加名字
UILabel * namelable = [[UILabel alloc] init];
//设置位置
CGFloat nameW = appW;
CGFloat nameH = 20;
CGFloat nameX = 0;
CGFloat nameY = iconY + iconH;
namelable.frame = CGRectMake(nameX, nameY, nameW, nameH);
//设置文字
namelable.text = appInfo[@"name"];
//设置字体
namelable.font = [UIFont systemFontOfSize:12];
//设置文字剧中
namelable.textAlignment = NSTextAlignmentCenter;
[appView addSubview:namelable];
//添加下载按钮
UIButton * downloaBtn = [[UIButton alloc] init];
//设置位置
CGFloat downloadX = 12;
CGFloat downloadY = nameY +nameH;
CGFloat downloadW = appW - 2 * downloadX;
CGFloat downloadH = 20;
downloaBtn.frame = CGRectMake(downloadX, downloadY, downloadW, downloadH);
//设置默认背景
[downloaBtn setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal];
[downloaBtn setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted];
[downloaBtn setTitle:@"下载" forState:UIControlStateNormal];
[appView addSubview:downloaBtn];
}
}
-(NSArray *)apps
{
if (_apps ==nil) {
//初始化
//1.获取plist的全路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil];
//2.加载数组
_apps = [NSArray arrayWithContentsOfFile:path];
}
return _apps;
}
执行效果:
iOS开发UI篇章之应用管理的九宫格坐标计算