Search code examples
iosnsattributedstringnsparagraphstyle

iOS why NSParagraphStyle resets the original text styles


I use UILabel's attributedText to load a HTML string, for example:

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

And I use NSParagraphStyle to change the line-height of all elements of this HTML.

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.


Solution

  • 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.

    [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];
        }
    }];