在中心文本对齐时获取UILabel文本行的框架

时间:2016-08-03 08:00:49

标签: ios uilabel core-text textkit

我的标签尺寸为W= 190 H =322,标签中的文字位于中心对齐方式,如enter image description here

我想要一个来自UILabel的文本框架的橙色框字符

1 个答案:

答案 0 :(得分:0)

UILabel的框架尺寸应与我的内容相同。包裹。 你就是这样做的:

没有自动布局:

您应该在UILabel上调用sizeToFit将其缩小为文本大小,然后选中I&#t。ts frame。

textLabel.text = "@yourText";
textLabel.numberOfLines = 1;
[textLabel sizeToFit];
CGSize size = CGSizeMake(textLabel.frame.size.width, textLabel.frame.size.height);

使用自动布局:

只需设置" numberOfLines"为0,并且不给标签一个宽度约束,标签大小将自动适合。

修改

核心文字:

UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.text = @"Your text";
float yourFontSize = 20;
while ([label.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:yourFontSize]}].width > modifierFrame.size.width)
{
     yourFontSize--;
}
label.font = [UIFont systemFontOfSize:yourFontSize];