1

Hi I am new to objective C. I am converting htmlString into NSMutableAttributedString. but when i changed font size of NSMutableAttributedString it removes bold font from my text, kindly give any solution.

My code:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding]  options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil ];



        if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
        {
//            overView.font = [UIFont systemFontOfSize:16];
            [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, attributedString.length)];
        }
        else{
//            overView.font = [UIFont systemFontOfSize:12];
            [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, attributedString.length)];
        }
        overView.attributedText = (NSAttributedString *)attributedString;

Any help would be appreciated thanks.

Furqan
  • 787
  • 2
  • 13
  • 28
  • Not **it**, you do. There is also a `boldSystemFontOfSize` method. – vadian Apr 24 '17 at 09:12
  • @vadian it will bold all string. – Furqan Apr 24 '17 at 09:21
  • Of course, because the range is specified for the whole string. If you want a partial string you have to adjust the range. – vadian Apr 24 '17 at 09:23
  • Actually I am getting htmlString from API and it has some formatting like some lines are surrounded by and some are italic. I just convert it into NSMutableAttributedString. and after this I want to change font size of string according to iPad or iPhone. @vadian – Furqan Apr 24 '17 at 09:26

1 Answers1

1

Try this. You need to use copy string to show changed string.

  NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding]  options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil ];
  NSMutableAttributedString* copy = [attributedString mutableCopy];
  [attributedString enumerateAttributesInRange:NSMakeRange(0, string.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
    UIFont* font = attrs[NSFontAttributeName];
    if(font)
    {
      NSMutableDictionary* changedAttributes = [attrs mutableCopy];
      if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
      {
        changedAttributes[NSFontAttributeName] = [UIFont fontWithName:font.fontName size:16];
      }
      else{
        changedAttributes[NSFontAttributeName] = [UIFont fontWithName:font.fontName size:12];
      }
      [copy setAttributes:changedAttributes range:range];
    }
  }];
Sergey
  • 1,589
  • 9
  • 13