繁体   English   中英

如何为NSAttributedString设置默认字体

[英]How to set default font for NSAttributedString

根据apple的文档,如果你没有为给定范围的属性字符串提供任何字体,默认情况下它将采用大小为12的Helvetica字体。

现在我想要更改默认字体。 任何人都可以建议我如何做到这一点。

其实我想实现以下目标:

我有html的字符串(来自服务器的动态html),让它说为htmlStr 在此字符串中,可能已为html的不同部分设置了字体,并且可能没有为该htmlStr设置任何字体。

现在,我要秀+编辑这个htmlStr,所以首先我对设置这个htmlStr转换成attributedString,然后显示它在TextView中attributedText为TextView的。

现在我的问题是,如果没有为这个htmlStr提供任何字体,它采用默认字体,这个字体太小而且看起来不太好。 那么,如何更改属性字符串的默认字体。

尝试

目标 - C.

__block BOOL found = NO;
    NSMutableAttributedString *attrString = ...
[attrString beginEditing];
    [attrString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attrString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
        if (value) {
            UIFont *oldFont = (UIFont *)value;
            UIFont *newFont = [oldFont fontWithSize:oldFont.pointSize * 2];
            [attrString addAttribute:NSFontAttributeName value:newFont range:range];
            found = YES;
        }
    }];
    if (!found) {
        // No font was found - do something else?
    }
    [attrString endEditing];

斯威夫特4

var found = false
var attrString = NSMutableAttributedString()

attributedText.enumerateAttribute(NSAttributedStringKey.font, in: NSMakeRange(0, attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) in
        if let oldFont = value as? UIFont {
            let newFont = oldFont.withSize(oldFont.pointSize * 2)
            attributedText.addAttribute(NSAttributedStringKey.font, value: newFont, range: range)
            found = true
        }
    }

    if !found {
        // No font was found - do something else?
    }

attributedText.endEditing()
    Try this one also:-

- (NSAttributedString *) convertToAttributedString: (NSString *) string withStringToConvert: (NSString *) str2 {
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:string];
    [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, string.length)];
    [attributedStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:FONT_APPLE_SD_GOTHIC_NEO_BOLD size:17.0] range:NSMakeRange(0, string.length)];

    [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(0,str2.length)];
    [attributedStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:FONT_APPLE_SD_GOTHIC_NEO size:17.0] range:NSMakeRange(0, str2.length)];

    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:3];
    [attributedStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, string.length)];

    return attributedStr;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM