UIStackView *mainStackView = [[UIStackView alloc] init];
mainStackView.axis = UILayoutConstraintAxisVertical;
mainStackView.spacing = 20;
mainStackView.alignment = UIStackViewAlignmentFill;
mainStackView.distribution = UIStackViewDistributionFill;
MyFlowLayout *flowLayout = [[MyFlowLayout alloc] initWithOrientation:MyOrientation_Vert arrangedCount:0];
flowLayout.subviewSpacing = 8;
flowLayout.wrapContentHeight = YES;
flowLayout.backgroundColor = [UIColor orangeColor];
for (NSInteger i = 0; i < 5; i++) {
NSArray *titles = @[
@"123",
@"ABCDEF",
@"这里可以看到尺",
@"宽度等于自己的尺寸",
@"则按钮的宽度就是内容的宽度",
];
NSInteger index = arc4random()%titles.count;
UIButton *tagButton = [UIButton new];
[tagButton setTitle:titles[index] forState:UIControlStateNormal];
tagButton.layer.cornerRadius = 15;
tagButton.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:((arc4random()%10)*0.1+0.05)];
tagButton.widthSize.equalTo(@(MyLayoutSize.wrap)).add(10).min(40);
tagButton.heightSize.equalTo(@(MyLayoutSize.wrap)).add(10);
[tagButton sizeToFit];
[flowLayout addSubview:tagButton];
}
[mainStackView addArrangedSubview:flowLayout];
代码: