3

设置UILabel的属性文本并使用setFontSizeToFitWidth时,属性文本字体大小按预期调整大小。但是,当属性字符串字体大小调整为较小的字体大小时,文本不会在UILabel内部垂直对齐。垂直对齐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]; 

谁能帮助我实现这个目标,从而使文本也垂直对齐?

谢谢你们。

+0

这可能帮助你http://stackoverflow.com/questions/1054558/vertically-align-text -within-a-uilabel – iOSDeveloper

回答

1

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

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

像这样的东西应该被添加到您的代码的末尾,使这项工作,大概是:

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

谢谢你,伟大的解决方案! – michel