如何判断哪个iOS字体名称是字体系列中的“常规”版本?

时间:2013-01-29 17:50:16

标签: ios cocoa-touch fonts nsattributedstring

我知道我可以使用[UIFont familyNames]获取字体系列名称列表,并使用[UIFont fontNamesForFamilyName:]遍历系列的字体名称。有没有办法告诉哪个字体名称代表"正常"字体?命名中没有任何一致性(" Roman"," Regular",或者甚至没有修饰符形容词)。我最终试图在NSAttributedString的子字符串上更改字体,同时保持现有的特征和装饰。提前谢谢。

2 个答案:

答案 0 :(得分:1)

好吧,我需要更仔细地阅读CoreText文档。如果使用正确的CoreText例程,传入字体系列名就足够了......

NSString *fontFamilyName = ...(font family name)...;
// Make a mutable copy of the attributed text
NSMutableAttributedString *workingAttributedText = [self.attributedText mutableCopy];

// Over every attribute run in the selected range...
[workingAttributedText enumerateAttributesInRange:self.selectedRange
    options:(NSAttributedStringEnumerationOptions) 0
    usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
        // get the old font
        CTFontRef oldFont = (__bridge CTFontRef)[attrs objectForKey:NSFontAttributeName];
        // make a new one, with our new desired font family name
        CTFontRef newFontRef = CTFontCreateCopyWithFamily(oldFont, 0.0f, NULL, (__bridge CFStringRef)fontFamilyName);
        // Convert it to a UIFont
        UIFont *newFont = [UIFont fontWithCTFont:newFontRef];
        // Add it to the attributed text
        [workingAttributedText addAttribute:NSFontAttributeName value:newFont range:range];
    }];

// Replace the attributed text with the new version
[self setAttributedText:workingAttributedText];

如果有更简单的方法,我很乐意听到它。

答案 1 :(得分:0)

列表中不必有常规字体。有些可能只提供粗体或仅斜体。这就是为什么通常会向用户提供列表以让他们做出决定。