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;
}
執行效果:
轉載于:https://www.cnblogs.com/asd5551680/p/4013371.html