九宫格demo
2019-04-18 本文已影响0人
习惯了_就好
QQ20190418-225428@2x.png
@interface ViewController ()
@property(nonatomic,strong)NSArray * apps;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//每个容器宽高
CGFloat appW = 85;
CGFloat appH = 90;
//列数
int totalColumns = 3;
//每个item的间距
CGFloat marginX = (self.view.frame.size.width - appW * totalColumns) / (totalColumns + 1);
CGFloat marginY = 15;
//循环添加所有的item
for (int i = 0; i < self.apps.count; i++) {
//获取字典
NSDictionary * dic = self.apps[i];
UIView * view = [[UIView alloc]init];
//添加背景色
// view.backgroundColor = [UIColor redColor];
//计算位置,
CGFloat x = marginX + i / totalColumns * (appW + marginX);
CGFloat y = 50 + i % totalColumns * (appH + marginY);
view.frame = CGRectMake(x, y, appW, appH);
//添加子view
[self.view addSubview:view];
UIImageView * iconView = [[UIImageView alloc]init];
CGFloat iconW = 45;
CGFloat iconH = 45;
CGFloat iconX = (appW - iconW) / 2;
CGFloat iconY = 3;
//设置frame属性
iconView.frame = CGRectMake(iconX, iconY, iconW, iconH);
//给ImageView添加图片
iconView.image = [UIImage imageNamed:dic[@"icon"]];
[view addSubview:iconView];
UILabel * nameView = [[UILabel alloc] init];
//设置文字内容
nameView.text = dic[@"name"];
//设置文字对齐方式
nameView.textAlignment = NSTextAlignmentCenter;
CGFloat nameW = appW;
CGFloat nameH = 20;
CGFloat nameX = 0;
CGFloat nameY = iconH + 5;
nameView.frame = CGRectMake(nameX, nameY, nameW, nameH);
//设置文字大小
nameView.font = [UIFont systemFontOfSize:12];
//设置文字颜色
nameView.textColor = [UIColor blackColor];
[view addSubview:nameView];
UIButton * button = [[UIButton alloc] init];
CGFloat buttonW = appW - 20;
CGFloat buttonH = 20;
CGFloat buttonX = 10;
CGFloat buttonY = nameH + nameY;
button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
//设置按钮字体大小
button.titleLabel.font = [UIFont systemFontOfSize:12];
//设置按钮文字
[button setTitle:@"下载" forState:UIControlStateNormal];
//不要使用这种方式,没有设置状态会出问题
// button.titleLabel.text = "下载";
//设置背景图片
[button setBackgroundImage:[UIImage imageNamed:@"buttongreen" ]forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"buttongreen_height"] forState:UIControlStateHighlighted];
[view addSubview:button];
}
}
-(NSArray *)apps{
if (_apps == nil) {
//获取plist的全路径
NSString * path = [[NSBundle mainBundle] pathForResource:@"data.plist" ofType:nil];
_apps = [NSArray arrayWithContentsOfFile:path];
}
return _apps;
}
@end