牛骨文教育服务平台(让学习变的简单)
博文笔记

iOS 用For循环实现九宫格的实现

创建时间:2015-02-12 投稿人: 浏览次数:7213

 

    //      总列数
    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];
    }

 



声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。