九宫格算法

1.我们在做APP应用中经常需要去动态的排版九宫格列表的界面,所以我们需要了解九宫格的算法。
九宫格算法的核心思路:
列号计算:i % 列数 列号用来计算X
行号计算:i / 列数 行号用来计算Y

每一个应用视图的X = 左边距 + (应用视图的宽 + 应用左右间距)* 列号
每一个应用视图的Y = 上边距 + (应用视图的高 + 应用上下间距)* 行号

2.例子说明九宫格算法
效果图:
这里写图片描述

3.关键代码实现:

 //根据数据对象设计界面排版
    NSInteger columnCount = 3;
    //self.apps.count 是需要设置的应用图标个数
    for (NSInteger i = 0; i < self.apps.count; i++) {
        //创建一个视图
        UIView *appView = [[UIView alloc]init];
        //使用九宫格算法,排版视图
        //设置视图的宽
        CGFloat appViewW  = 100;
        //设置视图的高
        CGFloat appViewH  = 120;
        //计算列号
        NSInteger column = i % columnCount;
        //间隔
        CGFloat margin  = 20;
        //左边距
        CGFloat leftMargin = (self.view.bounds.size.width - appViewW * columnCount - margin * (columnCount -1)) * 0.5;
        //计算AppX
        CGFloat appViewX = leftMargin + (appViewW + margin) * column;
        //行号
        NSInteger row = i / columnCount;
        //上边距
        CGFloat topMargin = margin;
        //计算AppY
        CGFloat appViewY = topMargin + (appViewH + margin) * row;
        //设定appView的frame
        appView.frame = CGRectMake(appViewX, appViewY, appViewW, appViewH);

        //设置appView的属性
        appView.backgroundColor = [UIColor redColor];
        [self.view addSubview:appView];
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值