#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 设置每行应用的个数 int clumns = 3; // 获取控制器所管理的view的宽度 CGFloat viewWidth = self.view.frame.size.width; // 每个应用的宽和高 CGFloat appW = 75; CGFloat appH = 90; CGFloat marginTop = 30;//第一行距顶部的距离 CGFloat marginX = (viewWidth - appW*clumns)/(clumns+1); CGFloat marginY = marginX;//设每行之间的间距与marginX相等 for (int i=0; i<9; i++) { //1.创建每个应用(UIView) UIView *appView = [[UIView alloc] init]; //2.设置appView的属性 //2.1设置appView的背景色 appView.backgroundColor = [UIColor orangeColor]; //2.2设置appView的frame属性 //计算每个单元格的列索引 int colIdx = i%clumns; //计算每个单元格的行索引 int rowIdy = i/clumns; CGFloat appX = marginX+(appW+marginX)*colIdx; CGFloat appY = marginTop+(appH+marginY)*rowIdy; appView.frame = CGRectMake(appX, appY, appW, appH); //3.将appView加到self.view [self.view addSubview:appView]; } }
原文:http://www.cnblogs.com/oc-bowen/p/5084161.html