目标是在段落之间有一个行高比段落内高更大的单个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呈现所有三个段落。似乎无论我应用于字符串的第一段样式是什么,它都适用于后续的所有行和段落!
为什么不使用特殊的段落分隔符字符\u 2029,因为苹果在这里允许在一个NSAttributedString中使用多个段落样式?我不想闯入多个UILabels。
预先感谢所有对这一主题有深入核心知识的人。
发布于 2015-12-03 20:29:35
最后得到了这份工作。结果是,当我将后续UILabel上的对齐设置为.textAlignment = NSTextAlignmentCenter时,整个attributedText的段落样式都搞砸了。
因此,我们的经验是:如果您使用多个段落样式,不要在UILabel上设置任何相应的属性,否则您的行为将受到标签所看到的第一个段落样式的影响,即使属性不相关(例如,行高和文本对齐)。
https://stackoverflow.com/questions/34057161
复制相似问题