一個簡單的九宮格佈局
思路
- 利用控件的索引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]