九宫格计算思路
- 利用控件的索引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;
NSUInteger col = index % cols;
CGFloat shopX = col * (shopW + colMargin);
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];
}