近来需要做一个需求,就是可以输入新建多个标签,标签高度固定,但宽度不固定且个数不固定,效果图如下:
因此初步设想:使用UICollectionView的item自适应宽度,方法如下:
#import "TestCollectionCell.h"
@interface TestCollectionCell()
@property(nonatomic,weak)UILabel *yardLab;
@end
@implementation TestCollectionCell
- (instancetype) initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self setSubView];
}
return self;
}
- (void)setSubView{
CGFloat labH = 30.0;
UILabel *yardLab = [[UILabel alloc] init];
yardLab.textAlignment = NSTextAlignmentCenter;
self.yardLab = yardLab;
yardLab.layer.masksToBounds = YES;
yardLab.layer.cornerRadius = labH/2.0;
yardLab.backgroundColor = YardsColor;
// yardLab.text = @"22222222343423";
yardLab.font = SET_FONT(14.0);
[self.contentView addSubview:yardLab];
[yardLab mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.top.equalTo(self.contentView);
make.height.mas_equalTo(@(labH));
}];
yardLab.userInteractionEnabled = NO;
//删除按钮用自身
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTap:)];
[tapGestureRecognizer setNumberOfTapsRequired:1];
[yardLab addGestureRecognizer:tapGestureRecognizer];
CGFloat btnH = 18.0;
UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
deleteBtn.backgroundColor = [UIColor redColor];
self.deleteBtn = deleteBtn;
deleteBtn.hidden = YES;
deleteBtn.enabled = NO;
deleteBtn.layer.masksToBounds = YES;
deleteBtn.layer.cornerRadius = btnH/2.0;
[deleteBtn setBackgroundImage:[UIImage imageNamed:@"yard_delete"] forState:UIControlStateNormal];
// [deleteBtn addTarget:self action:@selector(managerAction:) forControlEvents:UIControlEventTouchUpInside];
[self.contentView addSubview:deleteBtn];
[deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.height.mas_equalTo(@(btnH));
make.right.equalTo(yardLab.mas_right).offset(btnH/3.0);
make.top.mas_equalTo(@(-btnH/2.0));
}];
}
#pragma mark — 实现自适应文字宽度的关键步骤:item的layoutAttributes
- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
[self setNeedsLayout];
[self layoutIfNeeded];
CGSize size = [self.contentView systemLayoutSizeFittingSize:layoutAttributes.size];
CGRect cellFrame = layoutAttributes.frame;
cellFrame.size.width = size.width + 16;
layoutAttributes.frame = cellFrame;
return layoutAttributes;
}
过程发现两个问题:
1、如果使用button,如下方法不能计算出宽度,要使用UILabel
2、如果只有一个item,会发现居中显示,但是并未发现UICollectionView有类似UILabel居左,居中,居右显示item的属性方法,效果图如下:
解决办法如下:
//collectionView的item只剩下一个时自动左对齐
SEL sel = NSSelectorFromString(@"_setRowAlignmentsOptions:");
if ([yardsCollection.collectionViewLayout respondsToSelector:sel]) {
((void(*)(id,SEL,NSDictionary*)) objc_msgSend)(yardsCollection.collectionViewLayout,sel, @{@"UIFlowLayoutCommonRowHorizontalAlignmentKey":@(NSTextAlignmentLeft),@"UIFlowLayoutLastRowHorizontalAlignmentKey" : @(NSTextAlignmentLeft),@"UIFlowLayoutRowVerticalAlignmentKey" : @(NSTextAlignmentCenter)});
}
最终效果: