欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

九宫格

程序员文章站 2022-06-14 13:38:01
...

算法:核心点就是算x,y.控件在第index / cols行,第index % cols列。

 // 每一个商品的尺寸
    CGFloat shopW = 50;
    CGFloat shopH = 70;
    
    // 一行的列数
    int cols = 4;
    
    // 每一列之间的间距
    CGFloat colMargin = (self.shopsView.frame.size.width - cols * shopW) / (cols - 1);
    // 每一行之间的间距
    CGFloat rowMargin = 10;
    
    // 创建一个父控件(整体:存放图片和文字)
    UIView *shopView = [[UIView alloc] init];
    shopView.backgroundColor = [UIColor redColor];
    
    
    
    // 商品的索引
    NSUInteger index = self.shopsView.subviews.count;
    
    // 商品的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];
    

    // 添加图片
    UIImageView *iconView = [[UIImageView alloc] init];
    iconView.image = [UIImage imageNamed:@"danjianbao"];
    iconView.frame = CGRectMake(0, 0, shopW, shopW);
    iconView.backgroundColor = [UIColor blueColor];
    [shopView addSubview:iconView];
    
    // 添加文字
    UILabel *label = [[UILabel alloc] init];
    label.text = @"单肩包";
    label.frame = CGRectMake(0, shopW, shopW, shopH - shopW);
    label.font = [UIFont systemFontOfSize:11];
    label.textAlignment = NSTextAlignmentCenter;
    [shopView addSubview:label];