Обработка UIContentSizeCategoryDidChangeNotification для NSAttributedString в UITextView

У меня есть NSAttributedString в UITextView и я хотел бы обрабатывать UIContentSizeCategoryDidChangeNotification при работе с Dynamic Type и, в частности, с текстовыми стилями. Все примеры, которые я видел (IntroToTextKitDemo), относятся к случаю, когда шрифт одинаковый для всего элемента интерфейса. Кто-нибудь знает, как правильно это обрабатывать, чтобы все атрибуты обновлялись правильно?

Примечание. Я спросил об этом на форумах разработчиков, когда iOS 7 находилась под NDA. Я размещаю его здесь, потому что нашел решение и подумал, что другие могут найти его полезным.

Ответы

Ответ 1

Я нашел решение. При обработке уведомления вам нужно пройти атрибуты и искать стили текста и обновлять шрифт:

- (void)preferredContentSizeChanged:(NSNotification *)aNotification
{
    UITextView *textView = <the text view holding your attributed text>

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];
    NSRange range = NSMakeRange(0, attributedString.length - 1);

    // Walk the string attributes
    [attributedString enumerateAttributesInRange:range options:NSAttributedStringEnumerationReverse usingBlock:
     ^(NSDictionary *attributes, NSRange range, BOOL *stop) {

         // Find the font descriptor which is based on the old font size change
         NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes];
         UIFont *font = mutableAttributes[@"NSFont"];
         UIFontDescriptor *fontDescriptor = font.fontDescriptor;

         // Get the text style and get a new font descriptor based on the style and update font size
         id styleAttribute = [fontDescriptor objectForKey:UIFontDescriptorTextStyleAttribute];
         UIFontDescriptor *newFontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle:styleAttribute];

         // Get the new font from the new font descriptor and update the font attribute over the range
         UIFont *newFont = [UIFont fontWithDescriptor:newFontDescriptor size:0.0];
         [attributedString addAttribute:NSFontAttributeName value:newFont range:range];
     }];

    textView.attributedText = attributedString;
}