一个简单的九宫格布局
思路
- 利用控件的索引index计算出控件所在的行号和列号
- 利用列号计算控件的x值
- 利用行号计算控件的y值
需要设置一些固定值
图片长宽 : NSInteger cols = 3;
布局列数 :NSInteger imageW = 100; NSInteger imageH = 100;
计算每张图片应该放在第几行和第几列
NSInteger col = index % cols;
NSInteger row = index / cols;
计算图片布局间距
CGFloat colMargin = (bgView.bounds.size.width - cols *imageW) / (cols - 1);
计算图片所在的x和y坐标
CGFloat shopX = col * (imageW +colMargin);
CGFloat shopY = row * (imageH + colMargin);
创建控件,并添加到视图上(图片名称为:imageX)
UIImageView *imageView =[[UIImageView alloc]init];
imageView.frame = CGRectMake(shopX, shopY, imageW, imageH);
[imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"Image%ld",index]]];
[bgView addSubview:imageView];
整体代码
- (void)viewDidLoad {
[super viewDidLoad];
for (NSInteger i = 0; i<9; i++) {
[self showImageView:self.view withImageIndex:i];
}
}
- (void)showImageView:(UIView *)bgView withImageIndex:(NSInteger)index{
//一行的列数
NSInteger cols = 3;
//图片大小
NSInteger imageW = 100;
NSInteger imageH = 100;
//每一列的间距
CGFloat colMargin = (bgView.bounds.size.width - cols *imageW) / (cols - 1);
//图片所在列
NSInteger col = index % cols;
//图片所在行
NSInteger row = index / cols;
CGFloat shopX = col * (imageW +colMargin);
CGFloat shopY = row * (imageH + colMargin);
UIImageView *imageView =[[UIImageView alloc]init];
imageView.frame = CGRectMake(shopX, shopY, imageW, imageH);
[imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"Image%ld",index]]];
[bgView addSubview:imageView];
}
附上demo:[ ImageLayout]