Masonry 布局不等宽的标签并自动换行

2018-05-24 17:46:22 浏览数 (1)

效果

image.png

demo
代码语言:javascript复制
NSArray *array = @[@"一",@"二二",@"三三三",@"四四四四",@"五五五五五",@"一",@"二二",@"三三三",@"四四四四",@"五五五五五",@"一",@"二二",@"三三三",@"四四四四",@"五五五五五",@"一",@"二二",@"三三三",@"四四四四",@"五五五五五"];
    
    UIButton *listButton;
    
    __block float buttonRight;
    
    for (int i = 0; i < array.count; i  ) {
        
        NSString *title = array[i];
        
        CGFloat titleW = [title sizeWithFont:Font(14) maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)].width   20;
        
        UIButton *button = [UIButton new];
        button.backgroundColor = WHColor_1779ff;
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:WhiteColor forState:UIControlStateNormal];
        button.titleLabel.font = Font(14);
        button.layer.cornerRadius = 10;
        button.layer.masksToBounds = YES;
        [self addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            
            if (listButton) {
                
                buttonRight = buttonRight   15   titleW;
                
                if (buttonRight > SCREEN_WIDTH) {
                    //下一排的第一个
                    make.top.mas_equalTo(listButton.mas_bottom).offset(15);
                    make.left.mas_equalTo(self.tagImageView).offset(0);
                    buttonRight = 30   titleW;
                }else{
                    //非第一个
                    make.top.mas_equalTo(listButton.mas_top).offset(0);
                    make.left.mas_equalTo(listButton.mas_right).offset(15);
                }
                
                
                
            }else{
                //第一个
                
                make.top.mas_equalTo(tagView.mas_bottom).offset(25);
                make.left.mas_equalTo(self.tagImageView).offset(0);
                buttonRight = 30   titleW;
            }
            make.size.mas_equalTo(CGSizeMake(titleW, 20));
            
            
        }];
        
        listButton = button;
        
        
    }

0 人点赞