我正在从 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 - 换行符在 UILabel 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2555621/