如何设置默认字体NSAttributedString
按照苹果的文档,如果你不提供属性串的给定范围内的任何字体,默认情况下它会采取大小12如何设置默认字体NSAttributedString
现在RightNow公司的Helvetica字体我想改变这种状况默认字体。任何人都可以建议我,我该怎么做。
其实我想达到以下的事情:
我有HTML字符串(动态HTML从服务器推出),让说,它为htmlStr
。在这个字符串中,可能已经为html的不同部分设置了字体,并且也可能没有为该htmlStr设置任何字体。
现在,因为我想要显示+编辑此htmlStr,所以首先我将这个htmlStr转换为attributesString,然后通过为textview设置attributedText
在textview中显示它。
现在我的问题是,如果没有为这个htmlStr提供任何字体,它会采用默认字体太小的尺寸和不好看。所以,我怎样才能改变这个默认的字体为属性的字符串。
尝试
的Objective - 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()
感谢@Piyush,让我把它转换成swift,让我试试看,如果工作正常,那么一定会upvote你。 –
你应该给'swift'标签问题:) :) –
其实swift或objective-c无关紧要,我们只需要从一个转换到另一个,但需要获得解决方案 –
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;
}
要么编辑HTML字符串强制字体大小,或枚举attributedString和添加正确的字体。 – Larme
如何枚举归档字符串以检查字体? –
实际上html是来自任何随机地方,所以我们不能强制他们从服务器,要么我们可以通过添加一些默认的字体(我不知道很多关于HTML,所以要求)更新HTML或我需要更新默认字体,但我无法做到。 –