九宫格 布局

九宫格.png

例子1

{
    // 一行最多4列
    int maxCols = 4;
    
    // 宽度和高度
    CGFloat buttonW = XMGScreenW / maxCols;
    CGFloat buttonH = buttonW;
    
    for (int i = 0; i<sqaures.count; i++) {
        // 创建按钮
        XMGSqaureButton *button = [XMGSqaureButton buttonWithType:UIButtonTypeCustom];
        // 监听点击
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        // 传递模型
        button.square = sqaures[i];
        [self addSubview:button];
        
        // 计算frame
        int col = i % maxCols;
        int row = i / maxCols;

        button.x = col * buttonW;
        button.y = row * buttonH;
        button.width = buttonW;
        button.height = buttonH;
        
        // 2.或者这个方法
//        self.height = CGRectGetMaxY(button.frame);
    }
    // 总行数
//    NSUInteger rows = sqaures.count / maxCols;
//    if (sqaures.count % maxCols) { // 不能整除, + 1
//        rows++;
//    }
    
    // 总页数 == (总个数 + 每页的最大数 - 1) / 每页最大数
    
    NSUInteger rows = (sqaures.count + maxCols - 1) / maxCols;
    
    // 计算footer的高度
    self.height = rows * buttonH;
    
    // 重绘
    [self setNeedsDisplay];
}

例子2

{
    // 每一个商品的尺寸
    CGFloat shopW = 80;
    CGFloat shopH = 90;
    
    // 一行的列数
    int cols = 3;
    
    // 每一列之间的间距
    CGFloat colMargin = (self.shopsView.frame.size.width - cols * shopW) / (cols - 1);
    // 每一行之间的间距
    CGFloat rowMargin = 10;
    
    // 创建一个父控件(整体:存放图片和文字)
    XMGShopView *shopView = [XMGShopView shopView];
    
    // 商品的索引
    NSUInteger index = self.shopsView.subviews.count;
    // 给商品控件传递商品模型
    shopView.shop = self.shops[index];
    
    // 商品的x值
    NSUInteger col = index % cols;
    CGFloat shopX = col * (shopW + colMargin);
    
    // 商品的y值
    NSUInteger row = index / cols;
    CGFloat shopY = row * (shopH + rowMargin);
    
    shopView.frame = CGRectMake(shopX, shopY, shopW, shopH);
    
    // 添加控件
    [self.shopsView addSubview:shopView];
    
    // 控制按钮的可用性
    [self checkState];
}

3.万能公式 计算九宫格高度

 // 一行最多4列
    int maxCols = 4;
 // 总页数 == (总个数 + 每页的最大数 - 1) / 每页最大数
    
    NSUInteger rows = (sqaures.count + maxCols - 1) / maxCols;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容