mic*_*hel 5 objective-c vertical-alignment nsattributedstring uilabel ios
设置UILabel的属性文本并使用setFontSizeToFitWidth时,属性文本字体大小按预期调整大小.但是,当属性字符串字体大小调整为较小的字体大小时,文本在UILabel内部不会垂直对齐.
我需要使用adjustFontSizeToFitWidth方法,因为属性字符串具有可变大小.我的最小字体大小设置为"15.0",最大字体大小设置为"28.0".因此我使用minimumScaleFactor"15.0/28.0"
我的代码:
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];
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我实现这一目标,以便文本也垂直对齐吗?
多谢你们.
首先,sizeToFit按照 XCodian 的评论指出的使用。这将确保标签自动调整为当前文本大小。
接下来,您需要将标签的框架垂直放置在其容器中(在您的示例中为self)。为了实现这一点,您可以使用 来添加约束[UIView addConstraint:]。
应该将类似这样的内容添加到代码末尾才能使其正常工作,可能是:
[self addConstraint:
[NSLayoutConstraint constraintWithItem:textLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]
];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6454 次 |
| 最近记录: |