これは、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で使用するために調整する必要があります。