iphone - 换行符在 UI​​Label 中不起作用

标签 iphone formatting uilabel

我正在从 plist 加载一些帮助文本,并以 UIScrollView 中的 UILabels 形式显示相同的帮助文本。部分代码如下:

 UILabel *sectionDetailLabel = [[[UILabel alloc] initWithFrame:CGRectMake(34, myOriginForThisSection, 286, 20)] autorelease];
    sectionDetailLabel.backgroundColor = [UIColor clearColor];
    sectionDetailLabel.numberOfLines = 0;
    sectionDetailLabel.font = [UIFont systemFontOfSize:12];
    sectionDetailLabel.textColor = [UIColor blackColor];
    sectionDetailLabel.textAlignment = UITextAlignmentLeft;
    sectionDetailLabel.lineBreakMode = UILineBreakModeWordWrap;

    [baseScrollView addSubview:sectionDetailLabel];

    [sectionDetailLabel setText:myStringForThisSection];
    [sectionDetailLabel sizeToFit];

虽然任何“长”文本都正确地包装成多行,但我无法使用“myStringForThisSection”中的换行符“\n”字符手动插入任何换行符。我只在 UILabel 中需要换行的地方看到字符“\”和“n”。

我查了一下,普遍的共识似乎是将 numberOfLines 设置为 0,将 lineBreakMode 设置为有效值并调用 sizeToFit (或根据 sizeWithFont: 设置 UILabel 的框架)应该可以。我似乎在上面的代码中执行了所有这些操作,并且在将未知长度的长字符串安装到 UILabel 上的多行中时效果非常好。那么这里可能缺少什么?

注意:所有使用的变量 - baseScrollView、myStringForThisSection 和 myOriginForThisSection - 均在上述代码开始执行之前加载,并且工作正常。

最佳答案

UILabel 不解释转义序列\n。您可以插入代表回车符和/或换行符的真实字符。创建一个字符来保存换行符,然后插入它。

unichar newLine = '\n';
NSString *singleCR = [NSString stringWithCharacters:&newLine length:1];
[myStringForThisSection insertString:singleCR atIndex:somePlaceIWantACR];

只要你的 myStringForThisSection 是可变的,就应该可以。

关于iphone - 换行符在 UI​​Label 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2555621/

相关文章:

iphone - phonegap 中#import "PhoneGapDelegate.h"错误消息?

C++ 如何格式化包含可变整数的文本行,使其在给定宽度内右对齐?

python - 在 Python 中将浮点列表转换为字符串

iphone - 直接访问Iphone 3gs相机

iphone - 分发证书未显示在钥匙串(keychain)访问中

SQL 可读性 : commas better at the end or at the beginning of select list?

ios - Storyboard - UILabel 自动收缩不起作用

ios - 淡出 UILabel 中最后 5 像素的文本

ios - 具有文本格式的多行 TableView 单元格

iphone - 可以将 UITableViewController 定制为非常紧凑/小的字体吗?