美文网首页
九宫格 布局

九宫格 布局

作者: 小的小碰撞 | 来源:发表于2017-08-29 15:29 被阅读0次
    九宫格.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;
    

    相关文章

      网友评论

          本文标题:九宫格 布局

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