// 总列数
int totalColumns = 3;
// 每一格的尺寸
CGFloat cellW = 80;
CGFloat cellH = 80;
// 间隙
CGFloat margin =(TheViewWithWidth - totalColumns * cellW) / (totalColumns + 1);
//根据格子个数创建对应的框框
for(int index = 0; index< 9; index++) {
UIButton *cellBtn = [[UIButton alloc ]init ];
cellBtn.backgroundColor = [UIColor redColor];
// 计算行号 和 列号
int row = index / totalColumns;
int col = index % totalColumns;
//根据行号和列号来确定 子控件的坐标
CGFloat cellX = margin + col * (cellW + margin);
CGFloat cellY = row * (cellH + margin);
cellBtn.frame = CGRectMake(cellX, cellY + 30, cellW, cellH);
cellBtn.tag = index;
[cellBtn addTarget:self action:@selector(cellBtnClick:) forControlEvents:UIControlEventTouchUpInside];
// 添加到view 中
[self addSubview:cellBtn];
}
九宫格
最新推荐文章于 2024-04-09 10:37:52 发布