导入plist文件,懒加载其数据,并使用九宫格公式,以及for循环的方式继续开发此项目。
------------- ViewController.m -------------
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) NSArray *apps;
@end
@implementation ViewController
- (NSArray *)apps
{
if(_apps == nil)
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"app" ofType:@"plist"];
_apps = [NSArray arrayWithContentsOfFile:path];
}
return _apps;
}
- (void)viewDidLoad
{
[super viewDidLoad];
CGFloat appW = 100;
CGFloat appH = 100;
int numOfCol = 3;
CGFloat marginX = (self.view.frame.size.width - appW * numOfCol) / (numOfCol + 1);
CGFloat marginY = 20;
for (int index = 0; index < self.apps.count; index++)
{
UIView *appView = [[UIView alloc] init];
int col = index % numOfCol;
CGFloat appX = marginX + (appW + marginX) * col;
int row = index / numOfCol;
CGFloat appY = 20 + marginY + (appH + marginY) * row;
appView.frame = CGRectMake(appX, appY,appW,appH);
[self.view addSubview:appView];
NSDictionary *app = self.apps[index];
UIImageView *imageView = [[UIImageView alloc] init];
CGFloat iconW = 50;
CGFloat iconH = 50;
CGFloat iconX = (appW - iconW) / 2;
CGFloat iconY = 0;
imageView.frame = CGRectMake(iconX,iconY , iconW, iconH);
[appView addSubview:imageView];
imageView.image = [UIImage imageNamed:app[@"icon"]];
UILabel *nameLabel = [[UILabel alloc] init];
CGFloat nameX = 0;
CGFloat nameY = CGRectGetMaxY(imageView.frame);
CGFloat nameW = appW;
CGFloat nameH = 20;
nameLabel.frame = CGRectMake(nameX, nameY, nameW, nameH);
[appView addSubview:nameLabel];
nameLabel.text = app[@"name"];
nameLabel.textAlignment = NSTextAlignmentCenter;
nameLabel.font = [UIFont systemFontOfSize:14];
UIButton *downloadBtn = [[UIButton alloc] init];
CGFloat downloadX = iconX;
CGFloat downloadY = CGRectGetMaxY(nameLabel.frame);
CGFloat downloadW = iconW;
CGFloat downloadH = appH - downloadY;
downloadBtn.frame = CGRectMake(downloadX, downloadY, downloadW, downloadH);
[appView addSubview:downloadBtn];
[downloadBtn setTitle:@"下载" forState:UIControlStateNormal];
[downloadBtn setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal];
[downloadBtn setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted];
}
}
@end