Reputation: 1816
I know that I can get a list of font family names with [UIFont familyNames]
and iterate through the family's font names with [UIFont fontNamesForFamilyName:]
. Is there any way to tell which font name represents the "normal" font? There isn't any consistency in the naming ("Roman", "Regular", or even the absence of a modifier adjective). I'm ultimately trying to change the font over a substring of an NSAttributedString
while maintaining existing traits and decorations. Thanks in advance.
Upvotes: 0
Views: 277
Reputation: 1816
Well, I need to read the CoreText docs more closely. Passing in the font family name is enough if you use the right CoreText routines...
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];
If there is an easier way to do this, I'd love to hear about it.
Upvotes: 1
Reputation: 8356
There doesn't have to be a regular font in the list. Some may only provide bold or only italic. This is why the list is often provided to the user to let them make the decision.
Upvotes: 0