淺析實現平鋪排列多個View的效果

weixin_34320159發表於2017-06-30

iPhone的螢幕規格越來越多,適配起來也要花一些時間

下面是我做起來的效果

在搜尋歷史的功能裡是用的比較多的

3463764-bb1c77483c0911ad.png
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() 就可以解決了。

相關文章