ios7 – 在UITextView中处理NSAttributedString的UIContentSizeCategoryDidChangeNotification

我在UITextView中有一个NSAttributedString,并且在处理动态类型,特别是文本样式时,希望处理UIContentSizeCategoryDidChangeNotification.我所看到的所有例子(IntroToTextKitDemo)解决了整个UI元素的字体是一样的.有没有人知道如何正确处理这些所有属性更新正确?

注意:当iOS 7处于NDA下时,我在开发者论坛上询问了这一点.我在这里发布,因为我找到一个解决方案,并认为其他人可能会发现它有用.

解决方法

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

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...