简体   繁体   English

iOS为什么NSParagraphStyle重设原始文字样式

[英]iOS why NSParagraphStyle resets the original text styles

I use UILabel 's attributedText to load a HTML string, for example: 我使用UILabelattributedText加载HTML字符串,例如:

<p style="text-align: center;">sometext</p>

And I use NSParagraphStyle to change the line-height of all elements of this HTML. 我使用NSParagraphStyle更改此HTML所有元素的line-height

NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.minimumLineHeight = 20; // line-height: 20;

[attributedString addAttribute:NSParagraphStyleAttributeName
                         value:paragraphStyle
                         range:NSMakeRange(0, attributedString.length)];

It works. 有用。 But it will reset the text-align to left. 但是它将重置text-align到左侧。

Attributes works like a Dictionary: Key/Value in a defined range. 属性的作用类似于定义范围内的字典:键/值。 There is unicity of the key, so you are overriding the value without copying its previous style. 密钥具有唯一性,因此您将覆盖值而不复制其先前样式。

To do what you want, you need to enumerate the attributed string looking for the NSParagraphStyleAttributeName and modify it if necessary. 要执行您想要的操作,您需要枚举属性字符串以查找NSParagraphStyleAttributeName并在必要时NSParagraphStyleAttributeName进行修改。

[attributedString enumerateAttribute:NSParagraphStyleAttributeName inRange:NSMakeRange(0, [attributedString length]) options:0 usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
    if ([value isKindOfClass:[NSParagraphStyle class]]) {
        NSMutableParagraphStyle *style = [value mutableCopy];
        style.minimumLineHeight = 20;
        [attributedString addAttribute:NSParagraphStyleAttributeName value:style range:range];
    }
}];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM