九宫格计算方式

九宫格计算思路

  • 利用控件的索引index计算出控件所在的行号和列号
  • 利用列号计算控件的x值
  • 利用行号计算控件的y值
- (void)add {
    // 每一个商品的尺寸
    CGFloat shopW = 70;
    CGFloat shopH = 90;

    // 一行的行数
    int cols = 3;

    // 每一列之间的间距
    CGFloat colMargin = (self.shopView.frame.size.width - cols * 70) / (cols - 1);

    // 创建父控件
    UIView *shopView = [[UIView alloc] init];
    shopView.backgroundColor = [UIColor redColor];

    // 商品的索引
    NSUInteger index = self.shopView.subviews.count;

    // 商品的x值
    NSUInteger col = index % cols;
    CGFloat shopX = col * (shopW + colMargin);

    // 商品的y值
    NSUInteger row = index / cols;
    CGFloat shopY = row * (shopH + colMargin);

    shopView.frame = CGRectMake(shopX, shopY, shopW, shopH);

    [self.shopView addSubview:shopView];

    // 添加图片
    UIImageView *icon = [[UIImageView alloc] init];
    icon.image = [UIImage imageNamed:@"danjianbao"];
    icon.frame = CGRectMake(0, 0, shopW, shopW);
    icon.backgroundColor = [UIColor greenColor];

    [shopView addSubview:icon];

    // 添加文字
    UILabel *label = [[UILabel alloc] init];
    label.text = @"单肩包";
    label.frame = CGRectMake(0, shopW, shopW, shopH - shopW);
    label.font = [UIFont systemFontOfSize:13];
    label.textAlignment = NSTextAlignmentCenter; // 文字居中

    [shopView addSubview:label];

    // 超出部分裁剪
//    self.shopView.clipsToBounds = YES;
}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值