如何为UILabel添加换行符? [英] How to add line break for UILabel?
问题描述
让我看到我的字符串如下所示:
Let see that I have a string look like this:
NSString *longStr = @"AAAAA\nBBBBB\nCCCCC";
如何让UILabel显示这样的信息
How do I make it so that the UILabel display the message like this
AAAAA
BBBBB
CCCCC
AAAAA
BBBBB
CCCCC
我不认为 \ n
被UILabel认可,所以我可以把任何东西都放在NSString里面,以便UILabel知道它有在那里创建换行符?
I don't think \n
is recognized by UILabel, so is there anything that I can put inside NSString so that UILabel knows that it has to create a line break there?
推荐答案
使用 \ n
as你在你的字符串中使用。
Use \n
as you are using in your string.
将numberOfLines设置为0以允许任意数量的行。
Set numberOfLines to 0 to allow for any number of lines.
label.numberOfLines = 0;
使用 sizeWithFont:
。如果你不这样做,你的文字将垂直居中或切断。
Update the label frame to match the size of the text using sizeWithFont:
. If you don't do this your text will be vertically centered or cut off.
UILabel *label; // set frame to largest size you want
...
CGSize labelSize = [label.text sizeWithFont:label.font
constrainedToSize:label.frame.size
lineBreakMode:label.lineBreakMode];
label.frame = CGRectMake(
label.frame.origin.x, label.frame.origin.y,
label.frame.size.width, labelSize.height);
更新:已弃用的替代
sizeWithFont:constrainedToSize :lineBreakMode:
参考,已弃用的替换sizeWithFont:在iOS 7中?
CGSize labelSize = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];
label.frame = CGRectMake(
label.frame.origin.x, label.frame.origin.y,
label.frame.size.width, labelSize.height);
这篇关于如何为UILabel添加换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!