- 首先解釋下%躺坟,/,的區(qū)別
/相當(dāng)于整數(shù)除法中的除號,%相當(dāng)于余號
5 除以 2 = 2 余 1,
因此 5/2=2,5%2=1.
- 代碼實現(xiàn)隨機的行數(shù)和列數(shù)
-(void)createNineView{
// 1-7隨機列數(shù)
int totalColumns = arc4random() % 7+1;
// 1-10 隨機行數(shù)
int totalRows = arc4random() % 10+1;
NSLog(@"列數(shù)--------%d-函數(shù)-------%d", totalColumns,totalRows);
// 每一格的尺寸
CGFloat cellW = 50;
CGFloat cellH = 50;
// 間隙
CGFloat marginX =(self.view.frame.size.width - totalColumns * cellW) / (totalColumns + 1);
CGFloat marginY = marginX;
// 根據(jù)格子個數(shù)創(chuàng)建對應(yīng)的框框
for(int index = 0; index< totalColumns*totalRows; index++) {
UIView *cellView = [[UIView alloc ]init ];
cellView.backgroundColor = [UIColor blueColor];
// 計算行號和列號
int row =index / totalColumns;
int col = index % totalColumns;
//根據(jù)行號和列號來確定 子控件的坐標
CGFloat cellX = marginX + col * (cellW + marginX);
CGFloat cellY = 70+row * (cellH + marginY);
cellView.frame = CGRectMake(cellX, cellY, cellW, cellH);
// 添加到view 中
[self.view addSubview:cellView];
}
}
- 擴展隨機數(shù)---擴展隨機