这是我在 DTrichTextEditor 中使用的:
- (void)toggleBoldInRange:(NSRange)range
{
// first character determines current boldness
NSDictionary *currentAttributes = [self typingAttributesForRange:range];
if (!currentAttributes)
{
return;
}
[self beginEditing];
CTFontRef currentFont = (__bridge CTFontRef)[currentAttributes objectForKey:(id)kCTFontAttributeName];
DTCoreTextFontDescriptor *typingFontDescriptor = [DTCoreTextFontDescriptor fontDescriptorForCTFont:currentFont];
// need to replace name with family
CFStringRef family = CTFontCopyFamilyName(currentFont);
typingFontDescriptor.fontFamily = (__bridge NSString *)family;
CFRelease(family);
typingFontDescriptor.fontName = nil;
NSRange attrRange;
NSUInteger index=range.location;
while (index < NSMaxRange(range))
{
NSMutableDictionary *attrs = [[self attributesAtIndex:index effectiveRange:&attrRange] mutableCopy];
CTFontRef currentFont = (__bridge CTFontRef)[attrs objectForKey:(id)kCTFontAttributeName];
if (currentFont)
{
DTCoreTextFontDescriptor *desc = [DTCoreTextFontDescriptor fontDescriptorForCTFont:currentFont];
// need to replace name with family
CFStringRef family = CTFontCopyFamilyName(currentFont);
desc.fontFamily = (__bridge NSString *)family;
CFRelease(family);
desc.fontName = nil;
desc.boldTrait = !typingFontDescriptor.boldTrait;
CTFontRef newFont = [desc newMatchingFont];
[attrs setObject:(__bridge id)newFont forKey:(id)kCTFontAttributeName];
CFRelease(newFont);
if (attrRange.location < range.location)
{
attrRange.length -= (range.location - attrRange.location);
attrRange.location = range.location;
}
if (NSMaxRange(attrRange)>NSMaxRange(range))
{
attrRange.length = NSMaxRange(range) - attrRange.location;
}
[self setAttributes:attrs range:attrRange];
}
index += attrRange.length;
}
[self endEditing];
}
这使用来自开源 DTCoreText 项目的 DTCoreTextFontDescriptor。
PS:您必须相应地调整它以与 UIFont 一起使用。