[英]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.