前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS-九宫格布局

iOS-九宫格布局

作者头像
xy_ss
发布2023-11-22 09:05:03
1370
发布2023-11-22 09:05:03
举报
文章被收录于专栏:浮躁的喧嚣浮躁的喧嚣
一个简单的九宫格布局

效果

思路
  • 利用控件的索引index计算出控件所在的行号和列号
  • 利用列号计算控件的x值
  • 利用行号计算控件的y值
需要设置一些固定值

布局列数: NSInteger cols = 3; 图片长宽 :NSInteger imageW = 100; NSInteger imageH = 100;

计算每张图片应该放在第几行和第几列
代码语言:javascript
复制
NSInteger col = index % cols;
NSInteger row = index / cols;
计算图片布局间距
代码语言:javascript
复制
CGFloat colMargin = (bgView.bounds.size.width - cols *imageW) / (cols - 1);
计算图片所在的x和y坐标
代码语言:javascript
复制
CGFloat shopX = col * (imageW +colMargin);
CGFloat shopY = row * (imageH + colMargin);
创建控件,并添加到视图上(图片名称为:imageX)
代码语言:javascript
复制
UIImageView *imageView =[[UIImageView alloc]init];
imageView.frame = CGRectMake(shopX, shopY, imageW, imageH);
[imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"Image%ld",index]]];
[bgView addSubview:imageView];
整体代码
代码语言:javascript
复制
- (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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-06-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一个简单的九宫格布局
  • 思路
  • 需要设置一些固定值
  • 计算每张图片应该放在第几行和第几列
  • 计算图片布局间距
  • 计算图片所在的x和y坐标
  • 创建控件,并添加到视图上(图片名称为:imageX)
  • 整体代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档