如何更改iOS中属性字符串的字体?

Dhe*_*mar -2 objective-c nsattributedstring ios

我在label上添加了属性字符串.我显示的html文本工作正常,但默认情况下它始终显示Times新罗马家族.请告诉我如何更改文本系列.

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[inst.desc dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
Run Code Online (Sandbox Code Playgroud)

Lor*_*eto 8

试试这个:

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;
Run Code Online (Sandbox Code Playgroud)

  • 如果有粗体或斜体效果,则会"删除"它. (3认同)

Piy*_*ush 5

你可以这样做:

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