美文网首页收藏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

    相关文章

      网友评论

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

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