//循环创建12个UiView
for (int i = 0; i < 12; i++) {
//设置每个View的大小
CGFloat viewW = 75;
CGFloat viewH = 90;
//设置距离上面的边距
CGFloat maginTop = 100;
//设置每一行有几个单元格
int culumns =3;
//设置每个单元格距离x坐标的距离(用自身的宽度 - 每一行有几个单元格)/(单元格的间距)---》》平均每个单元格间距
CGFloat maginX = (self.view.frame.size.width - (culumns*viewW))/(culumns+1);
//设置行索引
int cowIdx = i % culumns;
//设置列索引
int rowIdx = i / culumns;
//x坐标 = x坐标的间距 + 行索引*(每行单元格的大小)
CGFloat appX = maginX +cowIdx*(viewW + maginX);
//y坐标 = y坐标距离上面的间距 + 列索引*(每行单元格的个数)假设每个单元格的间距和x间距一样
CGFloat appY = maginTop + rowIdx * (viewH + maginX);
//设置frame
UIView *appView = [[UIView alloc] initWithFrame:CGRectMake(appX, appY, viewW, viewH)];
//设置背景颜色
appView.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.0];
//把子控件添加到容器内
[self.view addSubview:appView];
UI九宫格算法
最新推荐文章于 2024-03-21 12:35:00 发布