14

我在 UITextView 中有一个 NSAttributedString 并且想在使用动态类型特别是文本样式时处理 UIContentSizeCategoryDidChangeNotification。我见过的所有示例(IntroToTextKitDemo)都解决了整个 UI 元素的字体相同的情况。有谁知道如何正确处理这个问题,以便所有属性都能正确更新?

注意:当 iOS 7 处于保密协议下时,我在开发者论坛上问过这个问题。我在这里发布它是因为我找到了一个解决方案并认为其他人可能会觉得它有用。

4

1 回答 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;
}
于 2013-09-21T03:34:56.807 回答