iOS为什么NSParagraphStyle重置原始文本样式

iOS为什么NSParagraphStyle重置原始文本样式,ios,nsattributedstring,nsparagraphstyle,Ios,Nsattributedstring,Nsparagraphstyle,我使用UILabel的attributeText加载HTML字符串,例如: <p style="text-align: center;">sometext</p> 它起作用了。但它会将文本对齐重置为左侧。属性的工作原理类似于字典:键/值在定义的范围内。 键具有唯一性,因此您可以在不复制其先前样式的情况下重写该值 要执行所需操作,需要枚举属性字符串,查找NSParagraphStyleAttributeName,并在必要时对其进行修改 [attributedString

我使用
UILabel
attributeText
加载HTML字符串,例如:

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

它起作用了。但它会将
文本对齐
重置为左侧。

属性的工作原理类似于字典:键/值在定义的范围内。 键具有唯一性,因此您可以在不复制其先前样式的情况下重写该值

要执行所需操作,需要枚举属性字符串,查找
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];
    }
}];

这是正常行为,属性在一定范围内就像字典一样工作。因此,您只需覆盖
NSParagraphStyleAttributeName
值。相反,枚举寻找段落样式的属性,并更改其行高。这对我很有用。但效果不同于直接添加属性。我会用这种方法解决的。谢谢“但是效果不同于直接添加属性。”:我说了为什么不能这样做。另一种方法是直接修改html并应用一个(如果可能,我不熟悉html标记)。
[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];
    }
}];