九宫格计算思路
- 利用控件的索引index计算出控件所在的行号和列号
- 利用列号计算控件的x值
- 利用行号计算控件的y值
- (void)add {
// 每一个商品的尺寸
CGFloat shopW = ;
CGFloat shopH = ;
// 一行的行数
int cols = ;
// 每一列之间的间距
CGFloat colMargin = (self.shopView.frame.size.width - cols * ) / (cols - );
// 创建父控件
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(, , shopW, shopW);
icon.backgroundColor = [UIColor greenColor];
[shopView addSubview:icon];
// 添加文字
UILabel *label = [[UILabel alloc] init];
label.text = @"单肩包";
label.frame = CGRectMake(, shopW, shopW, shopH - shopW);
label.font = [UIFont systemFontOfSize:];
label.textAlignment = NSTextAlignmentCenter; // 文字居中
[shopView addSubview:label];
// 超出部分裁剪
// self.shopView.clipsToBounds = YES;
}
九宫格计算方式