【发布时间】:2015-12-03 03:08:15
【问题描述】:
目标是让单个 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。
在此先感谢在此主题上有深入核心文本知识的任何人。
【问题讨论】:
-
我认为它对我有用。尝试添加
@{NSBackgroundAttributeName:aDifferentColorForEachSubStringLikeTitleBodyTopBodyBottom}以查看它的作用,并尝试使用不同的lineHeightMultiple。 -
@Larme 是的,我已经设置了各种颜色和字体,没有任何问题。问题仅在于段落样式。你说它对你有用。介意发布一些适合您的示例代码吗?非常感谢。
标签: ios objective-c nsstring uilabel nsattributedstring