如何为NSAttributedString

时间:2017-06-13 11:00:41

标签: ios uitextview nsattributedstring nsmutableattributedstring

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

现在我想要更改默认字体。任何人都可以建议我怎么做。

其实我想要实现以下目标:

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

现在,因为我想显示+编辑这个htmlStr,所以首先我将这个htmlStr转换为attributedString,然后通过为textview设置attributedText在textview中显示它。

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

2 个答案:

答案 0 :(得分:2)

尝试

目标 - 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];

Swift 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()

答案 1 :(得分:0)

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