- (void)setupTitleLabel
{
for (NSInteger i = 0; i < self.titlesArray.count; i++) {
UILabel *label = [[UILabel alloc]init];
label.text = self.titlesArray[i];
label.tag = i;
label.backgroundColor = [UIColor orangeColor];
label.textAlignment = NSTextAlignmentCenter;
[self.titleScrollView addSubview:label];
[self.itemLabelArray addObject:label];
label.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
[label addGestureRecognizer:tap];
}
}
- (void)layoutSubviews
{
[super layoutSubviews];
NSInteger count = self.titlesArray.count;
CGFloat labelX = 0;
CGFloat labelY = 0;
CGFloat labelW = 0;
CGFloat labelH = self.frame.size.height;
CGFloat kMargin = 20;
for (NSInteger i = 0; i < count; i++) {
UILabel *lastLabel = i > 0 ? self.itemLabelArray[i - 1] : nil;
labelX = i == 0 ? kMargin * 0.5 : lastLabel.right + kMargin;
labelW = [self widthWithStr:self.titlesArray[i]];
UILabel *titleLabel = self.itemLabelArray[i];
titleLabel.frame = CGRectMake(labelX, labelY, labelW + 15, labelH);
}
// 思想:主要确定的是labelX,和labelW,只考虑第一个label的间隔kMargin * 0.5及其他label的间隔kMargin,剩下的由上一个label的右端 + kMargin为这一个label的labelX
UILabel *lastLabel = self.itemLabelArray[count - 1];
self.titleScrollView.contentSize = CGSizeMake(lastLabel.right + kMargin * 0.5, labelH);
}
- (CGFloat)widthWithStr:(NSString *)myStr
{
return [myStr boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName, nil] context:nil].size.width;
}
上述代码中lastLabel.right是由UIView+Common的一个category的方法
- (CGFloat)right
{
return self.frame.origin.x + self.frame.size.width;
}
获取的
效果如下