目标是让一个NSAttributedString在段落之间的行高大于段落内的行高,这在我看来是一个相当简单和常见的用例。这是我的代码:
NSMutableParagraphStyle *firstParagraphStyle = [[NSMutableParagraphStyle alloc] init];
firstParagraphStyle.lineHeightMultiple = 3.0;
NSMutableParagraphStyle *secondParagraphStyle = [[NSMutableParagraphStyle alloc] init];
secondParagraphStyle.lineHeightMultiple = 1.0;
NSAttributedString *title = [[NSAttributedString alloc] initWithString:@"Title"
attributes:@{NSParagraphStyleAttributeName: firstParagraphStyle}];
NSAttributedString *bodyTop = [[NSAttributedString alloc] initWithString:@"\u2029Body 1"
attributes:@{NSParagraphStyleAttributeName: secondParagraphStyle}];
NSAttributedString *bodyBottom = [[NSAttributedString alloc] initWithString:@"\u2029Body 2 line 1\u2028Body 2 line 2"
attributes:@{NSParagraphStyleAttributeName: secondParagraphStyle}];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
[attributedString appendAttributedString:title];
[attributedString appendAttributedString:bodyTop];
[attributedString appendAttributedString:bodyBottom];
所有四行最终都具有3.0的相同行间距。事实上,当我完全删除属性字典时,只需执行:
NSAttributedString *title = [[NSAttributedString alloc] initWithString:@"Title"];
NSAttributedString *bodyTop = [[NSAttributedString alloc] initWithString:@"\u2029Body 1"];
NSAttributedString *bodyBottom = [[NSAttributedString alloc] initWithString:@"\u2029Body 2 line 1\u2028Body 2 line 2"];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
[attributedString appendAttributedString:title];
[attributedString appendAttributedString:bodyTop];
[attributedString appendAttributedString:bodyBottom];
[attributedString addAttribute:NSParagraphStyleAttributeName
value:firstParagraphStyle
range:NSMakeRange(0, 1)];
[attributedString addAttribute:NSParagraphStyleAttributeName
value:secondParagraphStyle
range:NSMakeRange(1, attributedString.length - 1)];
仍然使用3.0行的行高倍数呈现所有三个段落。似乎无论我应用于字符串的第一段样式是什么,那是适用于所有后续行和段落的样式!
为什么不使用特殊paragraph separator character \u2029,因为Apple suggests here允许在单个NSAttributedString中使用多个段落样式?我不想闯入多个UILabel。
提前感谢任何对此主题有深入核心文本知识的人。
答案 0 :(得分:0)
结束了这项工作。当我将后续UILabel上的对齐设置为NotifyIcon
时,会弄乱整个.textAlignment = NSTextAlignmentCenter
的段落样式。
所以教训是:如果您使用多个段落样式,请不要在UILabel上设置任何相应的属性,否则您的行为将被标签看到的第一个段落样式破坏,即使属性没有关联(例如行高和文本对齐)。