iOS 知识点

浅析实现平铺排列多个View的效果

2017-06-30  本文已影响41人  小沛2016

iPhone的屏幕规格越来越多,适配起来也要花一些时间

下面是我做起来的效果

在搜索历史的功能里是用的比较多的

BDA01094-074E-42E0-8288-4FD3E22B8CF1.png

实现的代码也很简单 不用用CollectionView 也可以实现

- (void)initUICalculateContentHeightWithTagsArr:(NSArray *)tags maxWidth:(CGFloat)maxWidth labelHeight:(CGFloat)labelHeight clearanceWidth:(CGFloat)cw  clearanceHeight:(CGFloat)ch font:(NSInteger )font sampleLabel:(UILabel *)sampleLabel {
    
    //初始总高度
    CGFloat allHeight = 2*ch + labelHeight;
    
    CGFloat X = cw;
    CGFloat Y = ch;
    
    NSInteger count = tags.count;
    
    count>5?(count=5):(count=count);
    
    for (NSInteger i = 0; i < count; i++) {
        
        CGSize size = [tags[i][@"tag_name"] mm_sizeWithFont:[UIFont systemFontOfSize:font] constrainedToSize:CGSizeMake(MAXFLOAT, labelHeight)];
        
        size.width +=16;
        size.width = MIN(maxWidth, size.width);
        
        UILabel * l = [[UILabel alloc]init];

        l.text = tags[i][@"tag_name"];

        l.font = sampleLabel.font;

        l.backgroundColor = sampleLabel.backgroundColor;

        l.textColor       = sampleLabel.textColor;

        l.layer.cornerRadius  = 3;

        l.layer.masksToBounds = YES;

        l.textAlignment = NSTextAlignmentCenter;
        
        l.tag = 1000+i;
        
        
        if ((X + size.width + cw) > maxWidth) {
            
            X = cw;
            Y = Y + ch + labelHeight;
            
            allHeight = allHeight + ch + labelHeight;
            
        }
        //不取整 会有线
        l.frame = CGRectIntegral( CGRectMake(X, Y-ch, size.width, labelHeight) );
        X = X + size.width + cw;
        
        [self addSubview:l];
        
    }
    
    
}

这里有个bug就是如果宽高不取整的话 会有一条黑线出来 用CGRectIntegral() 就可以解决了。

上一篇下一篇

猜你喜欢

热点阅读