【问题标题】:Vertically align the attributed text within a UILabel垂直对齐 UILabel 中的属性文本
【发布时间】:2014-05-25 12:45:05
【问题描述】:

当设置 UILabel 的属性文本并使用 setFontSizeToFitWidth 时,属性文本字体大小会按预期调整。但是.. 当属性字符串字体大小调整为较小的字体大小时,文本在 UILabel 内没有垂直对齐。

我需要使用方法 adjustFontSizeToFitWidth 因为属性字符串的大小是可变的。我将最小字体大小设置为“15.0”,最大设置为“28.0”。因此我使用“15.0/28.0”的 minimumScaleFactor

我的代码:

NSAttributedString *balance = [[NSAttributedString alloc] initWithString:@"12390765298374652938756" attributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];

// Create UILabel with a 10.0 point padding around the UILabel within the parent Rect
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.bounds.origin.x + 10, self.bounds.origin.y + 10, self.bounds.size.width - 20, self.bounds.size.height - 20)];

textLabel.attributedText = currencyWithBalance;
textLabel.font = [UIFont fontWithName:@"TitilliumWeb-Light" size:28.0];
textLabel.minimumScaleFactor = 15.0/28.0;
textLabel.textAlignment = NSTextAlignmentCenter;
textLabel.adjustsFontSizeToFitWidth = YES;
textLabel.numberOfLines = 1;
textLabel.backgroundColor = [UIColor redColor];


[self addSubview:textLabel];

谁能帮我实现这一点,让文本也垂直对齐?

谢谢大家。

【问题讨论】:

标签: ios objective-c uilabel vertical-alignment nsattributedstring


【解决方案1】:

首先,使用sizeToFit,正如 XCodian 的评论所指出的那样。这将确保标签自行调整为当前的文本大小。

接下来,您需要将标签的框架垂直放置在其容器中(在您的示例中为self)。为此,您需要为此添加一个约束,使用 [UIView addConstraint:]

应该在代码末尾添加这样的内容以使其正常工作,可能是:

[self addConstraint:
  [NSLayoutConstraint constraintWithItem:textLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]
];

【讨论】:

  • 谢谢,很好的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 2010-11-06
相关资源
最近更新 更多