前言
项目中遇到一个多标签的需求,简单介绍下我的实现过程。
需求
具体需求是:
- 标签的个数不定,可能是0,1,2或3个;
- 将上述标签排列成一行;
- 标签的宽度随内容变化,其中文字距离左右是18,距离上下是8。
实现过程
- 针对标签内部的需求3,可以自定义HDTabLabel实现上下左右边距。
// HDTabLabel.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface HDTabLabel : UIView
@property (nonatomic, copy) NSString *text;
@end
NS_ASSUME_NONNULL_END
// HDTabLabel.m
#import "HDTabLabel.h"
@interface HDTabLabel ()
@property (nonatomic, strong) UILabel *textLabel;
@end
@implementation HDTabLabel
#pragma mark - initialize
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.layer.cornerRadius = 5;
self.layer.borderWidth = 1;
self.layer.borderColor = CGColorFromHex(0xE5E5E5);
self.layer.backgroundColor = CGColorFromHex(0xFFFFFF);
[self setupConstraintsForSubviews];
}
return self;
}
#pragma mark - setter
- (void)setText:(NSString *)text {
_text = text;
self.textLabel.text = text;
}
#pragma mark - layout subviews
- (void)setupConstraintsForSubviews {
[self addSubview:self.textLabel];
[self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_offset(8);
make.left.mas_offset(18);
make.bottom.mas_offset(-8);
make.right.mas_offset(-18);
}];
}
#pragma mark - lazy load
- (UILabel *)textLabel {
if (!_textLabel) {
_textLabel = [[UILabel alloc]init];
_textLabel.font = [UIFont italicSystemFontOfSize:15];
}
return _textLabel;
}
@end
- 针对需求1和需求2,是采用UIStackView的自动布局实现的,stackView的宽度由内部的子控件帮忙撑开(内容->Label的固有尺寸->撑开stackView),所以我们不要设置stackView的宽度约束。
#import "ViewController.h"
#import <Masonry.h>
#import "HDTabLabel.h"
@interface ViewController ()
@property (nonatomic, strong) UIStackView *stackView;
@end
@implementation ViewController
#pragma mark - life cycle
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor brownColor];
[self setupConstraintsForSubviews];
// 布局标签
NSArray *tabs = @[@"不懂拒绝",@"同情心泛滥",@"真诚"];
for (int i = 0; i < 3; i++) {
HDTabLabel *tabLabel = [[HDTabLabel alloc]init];
tabLabel.text = tabs[i];
[self.stackView addArrangedSubview:tabLabel];
}
}
#pragma mark - layout subviews
- (void)setupConstraintsForSubviews {
[self.view addSubview:self.stackView];
[self.stackView mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.mas_offset(0);
make.left.mas_offset(20);
}];
}
#pragma mark - lazy load
- (UIStackView *)stackView {
if (!_stackView) {
_stackView = [[UIStackView alloc]init];
_stackView.spacing = 15;
_stackView.axis = UILayoutConstraintAxisHorizontal;
_stackView.alignment = UIStackViewAlignmentFill;
_stackView.distribution = UIStackViewDistributionFillProportionally;
}
return _stackView;
}
@end