天天看點

iOS 用For循環實作九宮格的實作

//      總列數
    int totalColumns = 3;
    
    //       每一格的尺寸
    CGFloat cellW = 50;
    CGFloat cellH = 50;
    
    //    間隙
    CGFloat margin =(self.view.frame.size.width - totalColumns * cellW) / (totalColumns + 1);
    
    //    根據格子個數建立對應的框框
    for(int index = 0; index< self.array.count; index++) {
        UIView *cellView = [[UIView alloc ]init ];
        cellView.backgroundColor = [UIColor blueColor];
        
        // 計算行号  和   列号
        int row = index / totalColumns;
        int col = index % totalColumns;
        //根據行号和列号來确定 子控件的坐标
        CGFloat cellX = margin + col * (cellW + margin);
        CGFloat cellY = row * (cellH + margin);
        cellView.frame = CGRectMake(cellX, cellY, cellW, cellH);
        
        // 添加到view 中
        [self.view addSubview:cellView];
    }
           
iOS 用For循環實作九宮格的實作

繼續閱讀