0

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.

Larme
  • 24,190
  • 6
  • 51
  • 81
Jaycee
  • 23
  • 5
  • That's normal behavior, attributes work like a Dictionary in a range. So you just override the `NSParagraphStyleAttributeName` value. Instead, enumerate the attributes looking for the paragraph style, and change its line height. – Larme Jun 15 '18 at 09:17

1 Answers1

0

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];
    }
}];
Larme
  • 24,190
  • 6
  • 51
  • 81
  • it's useful for me. but the effect is not same as adding attribute dirctily. i will figure out it by this way. thanks! – Jaycee Jun 15 '18 at 10:32
  • "but the effect is not same as adding attribute dirctily.": I said why you can't do it. The other way is to modify directly the html and apply one (if possible, I'm not familiar with html tags). – Larme Jun 15 '18 at 10:34