#import "ViewController.h"
@interface ViewController() @property (nonatomic, strong) NSArray *appList; @end
@implementation ViewController
- (NSArray *)appList { if (!_appList) { // 1. 从mainBundle加载 NSBundle *bundle = [NSBundle mainBundle]; NSString *path = [bundle pathForResource:@"app.plist" ofType:nil]; _appList = [NSArray arrayWithContentsOfFile:path];
NSLog(@"%@", _appList); } return _appList; }
- (void)viewDidLoad { [super viewDidLoad]; // 九宫格总共有3列 int totalCol = 3; //每一个格子的宽度 CGFloat viewW = 80; //每一个格子的高度 CGFloat viewH = 90; //横向间距的设定,把整个屏幕视图的宽度减去三个格子的宽度,剩下的宽度平均分为四份 CGFloat marginX = (self.view.bounds.size.width - totalCol * viewW) / (totalCol + 1); //纵向间距的设定 CGFloat marginY = 10; //第一行方格的纵向坐标的开始位置 CGFloat startY = 20; //self.appList.count一共需要绘制的方格的总数 for (int i = 0; i < self.appList.count; i++) { // 行数 = 3 // i = 0, 1, 2 / 3 = 0 // i = 3, 4, 5 / 3 = 1 int row = i / totalCol; // 列数 = 3 // i = 0, 3, 6 % col 0 // i = 1, 4, 7 % col 1 // i = 2, 5, 8 % col 2 int col = i % totalCol; //设置方格的绝对坐标 CGFloat x = marginX + (viewW + marginX) * col; CGFloat y = startY + marginY + (viewH + marginY) * row; //绘制方格 UIView *appView = [[UIView alloc] initWithFrame:CGRectMake(x, y, viewW, viewH)]; //把视图控件添加到 appView [self.view addSubview:appView];
// 创建appView内部的细节 //读取数组中的字典 NSDictionary *dict = self.appList[i];
// UIImageView UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, viewW, 50)]; imageView.image = [UIImage imageNamed:dict[@"icon"]]; // 按照比例显示图像 imageView.contentMode = UIViewContentModeScaleAspectFit;
[appView addSubview:imageView];
//UILabel UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.bounds.size.height, viewW, 20)]; // 设置文字 label.text = dict[@"name"]; label.font = [UIFont systemFontOfSize:12.0]; label.textAlignment = NSTextAlignmentCenter;
[appView addSubview:label];
// UIButton // UIButtonTypeCustom和[[UIButton alloc] init]是等价的 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(15, 70, viewW - 30, 20);
[button setTitle:@"下载" forState:UIControlStateNormal]; // 不能使用如下代码直接设置title // button.titleLabel.text = @"下载"; // @property中readonly表示不允许修改对象的指针地址,但是可以修改对象的属性 button.titleLabel.font= [UIFont systemFontOfSize:14.0];
[button setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal]; [button setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted];
[appView addSubview:button];
} } |