9. 九宫格的计算思路

- (void)add

{

    // 每一个商品的尺寸

    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];

}

posted @ 2016-09-04 12:20  <瑾瑜>  阅读(161)  评论(0)    收藏  举报