【问题标题】:Change font size of NSMutableAttributedString without removing bold formatting. [duplicate]在不删除粗体格式的情况下更改 NSMutableAttributedString 的字体大小。 [复制]
【发布时间】:2017-09-20 21:15:45
【问题描述】:

您好,我是 Objective C 的新手。我正在将 htmlString 转换为 NSMutableAttributedString。但是当我更改 NSMutableAttributedString 的字体大小时,它会从我的文本中删除粗体字体,请提供任何解决方案。

我的代码:

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;

任何帮助将不胜感激。

【问题讨论】:

  • 不是,你知道。还有一个boldSystemFontOfSize方法。
  • @vadian 它会将所有字符串加粗。
  • 当然,因为范围是为整个字符串指定的。如果你想要一个部分字符串,你必须调整范围。
  • 实际上我是从 API 获取 htmlString 的,它有一些格式,比如有些行被 包围,有些是斜体。我只是将它转换为 NSMutableAttributedString。之后我想根据 iPad 或 iPhone 更改字符串的字体大小。 @vadian

标签: ios objective-c nsmutableattributedstring


【解决方案1】:

试试这个。您需要使用复制字符串来显示更改的字符串。

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

【讨论】:

  • 它不工作。
  • 您确定使用 copy 来显示字符串吗?因为这个对象的所有变化,不是一个属性字符串。
  • overView.attributedText = (NSAttributedString *)copy;我正在这样做。但不工作。
猜你喜欢
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 2016-11-22
  • 2013-05-14
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 2015-01-30
相关资源
最近更新 更多