@interface ViewController () /**获取.plist数据*/ @property (nonatomic,strong) NSArray *apps; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //九宫格的总列数 int totalColumns=5; //1.1个格子的尺寸 CGFloat appW=50; CGFloat appH=60; //2.计算间隙 =(控制器view的宽度 -5*应用宽度)/应用宽度+1 CGFloat margin=(self.view.frame.size.width-totalColumns*appW)/(totalColumns+1); //3.要的应用个数创建对应的格子 for (int index=0; index<self.apps.count; index++) { //3.1 创建1个格子 UIView *appView=[[UIView alloc]init]; //设置背景色 appView.backgroundColor=[UIColor whiteColor]; //3.2计算行号和列号 int row =index /totalColumns; int col =index % totalColumns; CGFloat appX =margin+ col*(appW + margin); CGFloat appY =margin+ row*(appH + margin); appView.frame=CGRectMake(appX, appY, appW, appH); //3.3添加格子到控制器的View [self.view addSubview:appView]; //3.4添加 内部的小控件 //取出index位置对应的应用信息 NSDictionary *appInfo=self.apps[index]; //3.4.1添加图片 UIImageView *iconView=[[UIImageView alloc]init]; CGFloat iconW=35; CGFloat iconH=35; CGFloat iconX=(appW-iconW)*0.5; CGFloat iconY=0; iconView.frame=CGRectMake(iconX, iconY, iconW, iconH); //iconView.backgroundColor=[UIColor grayColor]; iconView.image=[UIImage imageNamed:appInfo[@"icon"]]; [appView addSubview:iconView]; //3.4.2 添加名字 UILabel *nameLabel=[[UILabel alloc]init]; CGFloat namgeX=0; CGFloat nameY=iconY+iconH; CGFloat nameW=appW; CGFloat nameH=20; nameLabel.frame=CGRectMake(namgeX, nameY, nameW, nameH); nameLabel.backgroundColor=[UIColor greenColor]; nameLabel.text=appInfo[@"name"]; nameLabel.font=[UIFont systemFontOfSize:8];//设置字体大小 nameLabel.textAlignment=NSTextAlignmentCenter;//字体居中 [appView addSubview:nameLabel]; //3.4.3添加下载按钮 UIButton *downloadBtn=[[UIButton alloc]init]; CGFloat downloadX=5; CGFloat downloadY=nameY+nameH; CGFloat downloadW=appW-2*downloadX; CGFloat downloadH=20; downloadBtn.frame=CGRectMake(downloadX, downloadY, downloadW, downloadH); // downloadBtn.backgroundColor=[UIColor brownColor]; //设置按钮图片,普通状态 // downloadBtn.imageView.image=[UIImage imageNamed:@"buttongren"]; UIImage *normalImage=[UIImage imageNamed:@"buttongreen"]; [downloadBtn setBackgroundImage:normalImage forState:UIControlStateNormal]; //设置按钮图片,高亮状态 UIImage *highighedlImage=[UIImage imageNamed:@"buttongreen_highlighted"]; [downloadBtn setBackgroundImage:highighedlImage forState:UIControlStateHighlighted]; //设置按钮文字 //downloadBtn.titleLabel.text=@"下载"; [downloadBtn setTitle:@"下载" forState:UIControlStateNormal]; [downloadBtn setTitle:@"更新" forState:UIControlStateHighlighted]; //设置按钮文字的大小 downloadBtn.titleLabel.font=[UIFont systemFontOfSize:8]; [appView addSubview:downloadBtn]; } }