ios7 – 在UITextView中处理NSAttributedString的UIContentSizeCategoryDidChangeNotification

前端之家收集整理的这篇文章主要介绍了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;
}
原文链接:https://www.f2er.com/iOS/337503.html

猜你在找的iOS相关文章