美文网首页
UIView循环排列

UIView循环排列

作者: softgoto | 来源:发表于2016-12-01 18:00 被阅读0次

    项目中可能会遇到的一种排版方式,见图

    0C9007B3-B911-4D04-8366-83560D738B8E.png

    废话少说,直接上代码

    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, 300, 300)];
    bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.05];
    [self.view addSubview:bgView];
    
    for (int i = 1; i<=9; i++) {
        CGFloat width = 60;
        CGFloat height = 60;
        CGFloat spaceW = 10.0;
        
        UIView *view = [UIView new];
        view.frame = CGRectMake(0, 0, width, height);
        view.backgroundColor = [self randomColor];
        [bgView addSubview:view];
        
        // X = (当前下标-1)%每行显示数量*宽度 + (当前下标-1)%每行显示数量*间隙 + 间隙
        CGFloat x = (i-1)%4*width + (i-1)%4*spaceW + spaceW;
        
        // Y = (当前下标-1)/每行显示数量*高度 + (当前下标-1)/每行显示数量*间隙 + 间隙
        CGFloat y = (i-1)/4*height + (i-1)/4*spaceW + spaceW;
        view.frame = CGRectMake(x, y, width, height);
    }
    
    
    - (UIColor *)randomColor
    {
        CGFloat hue = ( arc4random() % 256 / 256.0 ); //0.0 to 1.0
        CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0,away from white
        CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; //0.5 to 1.0,away from black
        return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
    }
    

    相关文章

      网友评论

          本文标题:UIView循环排列

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