1. 程式人生 > >iOS中九宮格佈局

iOS中九宮格佈局

一個簡單的九宮格佈局

效果

思路

  • 利用控制元件的索引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];
}