【问题标题】:How change the font of attributed string in iOS? [duplicate]如何在 iOS 中更改属性字符串的字体? [复制]
【发布时间】:2023-04-08 03:12:01
【问题描述】:

我在标签上添加了属性字符串。我正在显示 html 文本,它工作正常,但默认情况下它总是显示 Times new roman family。请告诉我如何更改文本系列。

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[inst.desc dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

【问题讨论】:

  • 最快的方法是编辑 inst.desc 并以 HTML 格式样式添加它。否则,您将不得不枚举 NSFontAttributeName 的整个属性字符串。
  • 无法在你的代码中设置html内容

标签: ios objective-c nsattributedstring


【解决方案1】:

试试这个:

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[inst.desc dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
NSMutableAttributedString *newString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
NSRange range = (NSRange){0,[newString length]};
[newString enumerateAttribute:NSFontAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) {
    UIFont *replacementFont =  [UIFont fontWithName:@"Palatino-Roman" size:14.0];
    [newString addAttribute:NSFontAttributeName value:replacementFont range:range];
}];
self.label.attributedText = newString;

【讨论】:

  • 是的,您应该在分配属性字符串之后添加它。检查我编辑的答案
  • UIFont *font = [UIFont fontWithName:@"Palatino-Roman" size:14.0];我的字体是字体问题
  • 我不明白你的问题是什么。
  • 我添加了 UIfont 但 [newString addAttribute:NSFontAttributeName value:replacementFont range:range];显示字体错误
  • 如果有粗体或斜体效果,这将“删除”它。
【解决方案2】:

你可以这样做:

NSDictionary *attrDict = @{
    NSFontAttributeName : [UIFont fontWithName:Arial size:16.0],
    NSForegroundColorAttributeName : [UIColor redColor]
};
 NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"string" attributes:attrDict];

【讨论】:

  • html格式在哪里
猜你喜欢
  • 2016-05-20
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多