美文网首页收藏ios
iOS-九宫格布局

iOS-九宫格布局

作者: 皆为序幕_ | 来源:发表于2018-10-24 17:30 被阅读57次

一个简单的九宫格布局

效果

思路

  • 利用控件的索引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

相关文章

  • 详解自动布局(Masonry)实现九宫格

    以前写TimeLine中照片九宫格布局是直接计算frame,今天想用自动布局实现。 九宫格布局 使用自动布局,首先...

  • iOS-九宫格布局

    一个简单的九宫格布局 思路 利用控件的索引index计算出控件所在的行号和列号 利用列号计算控件的x值 利用行号计...

  • OC_九宫格布局工具

    实现基于: iOS Masonry九宫格布局 - 一行代码实现九宫格 demo点这里 以后你可能会这样布局九宫格 ...

  • Autolayout布局九宫格

    Autolayout纯代码布局九宫格 单行固定间隔排列: 水平布局设置 垂直布局设置 固定宽度设置: 水平布局 垂...

  • 02-UI基础第2天

    一、九宫格设计思路 根据九宫格内各控件的索引,先考虑行布局的问题,然后考虑列布局的问题 控件的整体性考虑,将控件组...

  • 九宫格布局

    九宫格布局 使用table实现 .parent{display:table;table-layout:fixed;...

  • flutter九宫格看图

    flutter九宫格图片 利用GridView实现布局,用Hero动画进行展示

  • 常见自适应布局/等分布局/九宫格布局

    自适应布局/等分布局/九宫格布局是面试常考的内容,通常要求掌握几种实现方法,以下是我自己准备秋招总结的布局,方便记...

  • SnapKit的扩展------添加数组控制约束,和九宫格布局,

    SnapKit的扩展------添加数组控制约束,和九宫格布局,等宽,等间距等布局方式 SnapKit是Swift...

  • Flex布局-产品介绍 & 网站 & 手机页面

    前言:Flex布局能快速实现常见的几种网页布局,如九宫格类产品介绍页面,网站双飞翼布局,手机页面设计等。 关于Fl...

网友评论

    本文标题:iOS-九宫格布局

    本文链接:https://www.haomeiwen.com/subject/hejhzftx.html