美文网首页
iOS开发 九宫格实现 (不同的行数和列数)

iOS开发 九宫格实现 (不同的行数和列数)

作者: 码农冰冰 | 来源:发表于2017-03-20 14:55 被阅读762次
  • 首先解释下%,/,的区别

/相当于整数除法中的除号,%相当于余号
5 除以 2 = 2 余 1,
因此 5/2=2,5%2=1.

  • 代码实现随机的行数和列数
-(void)createNineView{
    //      1-7随机列数
    int totalColumns = arc4random() % 7+1;
//        1-10 随机行数
    int totalRows = arc4random() % 10+1;
    NSLog(@"列数--------%d-函数-------%d", totalColumns,totalRows);
    //       每一格的尺寸
    CGFloat cellW = 50;
    CGFloat cellH = 50;
    //    间隙
    CGFloat marginX =(self.view.frame.size.width - totalColumns * cellW) / (totalColumns + 1);
    CGFloat marginY = marginX;
    //    根据格子个数创建对应的框框
    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;
        //根据行号和列号来确定 子控件的坐标
        CGFloat cellX = marginX + col * (cellW + marginX);
        CGFloat cellY = 70+row * (cellH + marginY);
        cellView.frame = CGRectMake(cellX, cellY, cellW, cellH);
        // 添加到view 中
        [self.view addSubview:cellView];  
    }
}
  • 扩展随机数---扩展随机

相关文章

网友评论

      本文标题:iOS开发 九宫格实现 (不同的行数和列数)

      本文链接:https://www.haomeiwen.com/subject/vdobnttx.html