我希望下面的标签(黄色)至少是两行而不是一行。
我确保在Interface Builder中取消选中Use Autolayout
。当我将numberOfLines
从0设置为2时,我会将两个单词堆叠在一起,黄色背景与单词紧密贴合。无论lineBreakMode
是NSLineBreakByWordWrapping
还是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
,结果只有一个行:
如何获得第二行? 解决方案此时,只需添加14
。
答案 0 :(得分:2)
如果您有静态文本,只需将break模式设置为wrap,将行设置为您想要的数字,然后在界面生成器中调整标签的框架,直到它以您喜欢的方式包装。你有动态文本,你可以在设置标签的文本后使用sizeToFit
让它自动调整它的高度以适应指定的宽度:
sizeToFit
答案 1 :(得分:1)
确定标签的最大宽度,并使用此值和NSLineBreakMode
尝试sizeWithFont:forWidth:lineBreakMode:
方法,以获取结果字符串边界框的大小。