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];
}

附上demo: ImageLayout

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容