效果:
代码实现:
#import "ViewController.h"
@interface ViewController () @property(nonatomic,strong)NSArray * apps; @end
@implementation ViewController
- (void)viewDidLoad { [super viewDidLoad]; [self apps];
CGFloat viewWith = 80; CGFloat viewHeight = 90; //第一行的View距离顶部的距离 CGFloat marginTop = 30;
//每一行上应用的个数,就是列数 int columns = 3;
//行数 int rownums=self.apps.count/columns+((self.apps.count % columns)==0?0:1); //marginX=(屏幕的宽度-viewWith*columns)/(columns+1) CGFloat marginX = (self.view.frame.size.width-viewWith*columns)/(columns+1); //marginY间距 CGFloat marginY = (self.view.frame.size.height-viewHeight*rownums)/(rownums);
for(int i= 0;i<self.apps.count;i++){
//创建view显示在屏幕上 UIView *appView = [[UIView alloc]init];
//计算当前各自所在的列索引 int col = i%columns;
//计算当前各自的行索引 int row = i/columns;
//设置view的frame
CGFloat X =marginX*(col+1)+viewWith*(col); CGFloat Y =marginTop+marginY*(row)+viewHeight*(row);
appView.frame=CGRectMake(X, Y, viewWith, viewHeight);
//将appview添加到控制器的view里 [self.view addSubview:appView]; NSLog(@"appView=%@",appView);
//向appview中添加子控件 //创建UIImageView UIImageView *imageview = [[UIImageView alloc]init];
//设置UIImageView CGFloat iconW = 45; CGFloat iconH = 45; CGFloat iconX = (viewWith-iconW)/2; CGFloat iconY = 0; imageview.frame = CGRectMake(iconX, iconY, iconW, iconH); imageview.image = [UIImage imageNamed:self.apps[@"icon"]];
//添加UIImageView [appView addSubview:imageview];
//创建UILabel UILabel* label = [[UILabel alloc]init]; //设置UILabel CGFloat nameW = viewWith; CGFloat nameH = 20; CGFloat nameX = 0; CGFloat nameY = iconH; label.frame = CGRectMake(nameX, nameY, nameW, nameH); // 修改label的样式 label.font = [UIFont systemFontOfSize:12]; label.textAlignment = NSTextAlignmentCenter;//居中
label.text=self.apps[@"name"];
//添加UILabel [appView addSubview:label];
//创建UIButton UIButton * button = [[UIButton alloc]init]; //设置UIButton CGFloat btnDownloadW = viewWith; CGFloat btnDownloadH = 20; CGFloat btnDownloadX = 0; CGFloat btnDownloadY = nameY +nameH; button.frame = CGRectMake(btnDownloadX, btnDownloadY, btnDownloadW, btnDownloadH); [button setTitle:@"下载" forState:UIControlStateNormal]; [button setTitle:@"已安装" forState:UIControlStateDisabled]; button.titleLabel.font=[UIFont systemFontOfSize:12]; [button setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal]; [button setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted]; //添加UIButton
[appView addSubview:button]; [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchDown]; }
} -(void)button:(UIButton*)sender { sender.enabled=NO; }
- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; -(NSArray *)apps { if(_apps==nil) { NSString *path = [[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil]; _apps = [NSArray arrayWithContentsOfFile:path]; } NSLog(@"%@",_apps); return _apps; } @end
|