在UITextView中处理NSAttributedString的UIContentSizeCategoryDidChangeNotification

14
我在UITextView中有一个NSAttributedString,希望在使用动态类型并特别处理文本样式时,能够处理UIContentSizeCategoryDidChangeNotification。我看到的所有示例(IntroToTextKitDemo)都解决了字体在整个UI元素中是相同的情况。有人知道如何正确处理这种情况,以使所有属性都正确更新吗?
注:我曾在iOS 7保密协议下向开发者论坛提出过此问题。我在这里发布它,因为我找到了解决方案,认为其他人可能会发现它有用。
1个回答

10
我找到了一个解决方案。在处理通知时,您需要遍历属性并查找文本样式,并更新字体:
- (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's 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;
}

3
谢谢,非常有用。方法的第三行应该是NSRange range = NSMakeRange(0, attributedString.length);以覆盖整个文本。 - Smilin Brian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接