九宫格

来源:互联网 发布:js点击弹出再点击隐藏 编辑:程序博客网 时间:2024/04/29 23:47

    //      总列数
    int totalColumns = 3;
    
    //       每一格的尺寸
    CGFloat cellW = 80;
    CGFloat cellH = 80;
    //    间隙
    CGFloat margin =(TheViewWithWidth - totalColumns * cellW) / (totalColumns + 1);
    
    //根据格子个数创建对应的框框
    for(int index = 0; index< 9; index++) {
        UIButton *cellBtn = [[UIButton alloc ]init ];
        cellBtn.backgroundColor = [UIColor redColor];
        
        // 计算行号  和   列号
        int row = index / totalColumns;
        int col = index % totalColumns;
        //根据行号和列号来确定 子控件的坐标
        CGFloat cellX = margin + col * (cellW + margin);
        CGFloat cellY = row * (cellH + margin);
        cellBtn.frame = CGRectMake(cellX, cellY + 30, cellW, cellH);
        cellBtn.tag = index;
        [cellBtn addTarget:self action:@selector(cellBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        // 添加到view 中  
        [self addSubview:cellBtn];
    }