UILabel没有绘制多线

时间:2013-08-31 21:52:43

标签: ios

我希望下面的标签(黄色)至少是两行而不是一行。

problem

我确保在Interface Builder中取消选中Use Autolayout。当我将numberOfLines从0设置为2时,我会将两个单词堆叠在一起,黄色背景与单词紧密贴合。无论lineBreakModeNSLineBreakByWordWrapping还是NSLineBreakByTruncatingTail,结果都是相同的。如果我使用sizeWithAttributes的结果设置条件Label的框架也是一样的,如果我使用sizeToFit则不一样。我还尝试将标签设为UILabel而不是UILabel的子类,即TTTAttributedLabel,但结果是相同的。

_termsLabel.font = [UIFont systemFontOfSize:12];
_termsLabel.textColor = [UIColor grayColor];
_termsLabel.textAlignment = NSTextAlignmentCenter;
_termsLabel.lineBreakMode = NSLineBreakByWordWrapping;
_termsLabel.numberOfLines = 0;
_termsLabel.delegate = self;
_termsLabel.backgroundColor = [UIColor yellowColor];

// Terms label
NSString *termsText = [NSString stringWithFormat:@"%@ %@ %@ %@", NSLocalizedString(@"TermsIAgree", nil),
                                                                 NSLocalizedString(@"SettingsTOS", nil),
                                                                 NSLocalizedString(@"LocalizedAnd", nil),
                                                                 NSLocalizedString(@"SettingsPrivacyPolicy", nil)];

_termsLabel.text = termsText;
_termsLabel.linkAttributes = @{ (__bridge NSString *)kCTUnderlineStyleAttributeName : [NSNumber numberWithBool:YES]};
CGSize termsSize = [_termsLabel.text sizeWithAttributes: @{ NSFontAttributeName : _termsLabel.font}];
_termsLabel.frame = CGRectMake(65,
                               395,
                               termsSize.width, termsSize.height);

[_termsLabel addLinkToURL:[NSURL URLWithString:TOS_URL] withRange:[termsText rangeOfString:NSLocalizedString(@"SettingsTOS", nil)]];
[_termsLabel addLinkToURL:[NSURL URLWithString:PRIVACY_POLICY_URL] withRange:[termsText rangeOfString:NSLocalizedString(@"SettingsPrivacyPolicy", nil)]];

编辑:使用CGSize termsSize = [_termsLabel.text sizeWithFont:_termsLabel.font forWidth:200 lineBreakMode:NSLineBreakByWordWrapping]; 查找字词大小然而height的{​​{1}}则为termsSize,结果只有一个行:

enter image description here

如何获得第二行? 解决方案此时,只需添加14

2 个答案:

答案 0 :(得分:2)

如果您有静态文本,只需将break模式设置为wrap,将行设置为您想要的数字,然后在界面生成器中调整标签的框架,直到它以您喜欢的方式包装。你有动态文本,你可以在设置标签的文本后使用sizeToFit让它自动调整它的高度以适应指定的宽度:

  1. 将框架设置为最大所需宽度
  2. 将行设置为0
  3. 设置中断模式以换行
  4. 致电sizeToFit

答案 1 :(得分:1)

确定标签的最大宽度,并使用此值和NSLineBreakMode尝试sizeWithFont:forWidth:lineBreakMode:方法,以获取结果字符串边界框的大小。