1 // 利用for循环创建九宫格 2 - (void)createScratchableLatex{ 3 4 // 总列数 5 int totalColumns = 3; 6 // 每一格的尺寸 7 CGFloat cellW = (self.frame.size.width-40)/totalColumns; 8 CGFloat cellH = 20; 9 // 竖直间隙 10 CGFloat verticalMargin = 10; 11 // 水平间隙 12 CGFloat transverseMargin = 5; 13 14 // 根据格子个数创建对应的框框 15 for(int index = 0; index< 9; index++) { 16 UIView *cellView = [[UIView alloc ]init ]; 17 cellView.backgroundColor = [UIColor redColor]; 18 int row = index / totalColumns; 19 int col = index % totalColumns; 20 CGFloat cellX = verticalMargin + col * (cellW + verticalMargin); 21 CGFloat cellY = row * (cellH + transverseMargin); 22 cellView.frame = CGRectMake(cellX, cellY, cellW, cellH); 23 [self addSubview:cellView]; 24 25 } 26 27 }