换行符在UILabel中不起作用

Dev*_*hen 5 iphone formatting uilabel

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

    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];
Run Code Online (Sandbox Code Playgroud)

虽然任何"长"文本都被正确地包装成多行,但我无法使用'myStringForThisSection'中的换行符'\n'来手动插入任何换行符.我只看到UILabel中打印的字符'\'和'n',而不是我想要的换行符.

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

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

小智 8

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

unichar newLine = '\n';
NSString *singleCR = [NSString stringWithCharacters:&newLine length:1];
[myStringForThisSection insertString:singleCR atIndex:somePlaceIWantACR];
Run Code Online (Sandbox Code Playgroud)

只要你的myStringForThisSection是可变的,那就应该这样做.