2013-09-21 12 views
14

Ho un NSAttributedString in un UITextView e desidero gestire UIContentSizeCategoryDidChangeNotification quando si lavora con il tipo dinamico e in particolare gli stili di testo. Tutti gli esempi che ho visto (IntroToTextKitDemo) indirizzano il caso in cui il carattere è lo stesso per l'intero elemento dell'interfaccia utente. Qualcuno sa come gestirlo correttamente in modo che tutti gli attributi vengano aggiornati correttamente?Gestione di UIContentSizeCategoryDidChangeNotification per NSAttributedString in UITextView

Nota: l'ho chiesto ai forum degli sviluppatori quando iOS 7 era in NDA. Lo sto postando qui perché ho trovato una soluzione e ho pensato che altri potrebbero trovare utile.

risposta

9

Ho trovato una soluzione. Quando si gestisce la notifica è necessario camminare gli attributi e cercare gli stili di testo e aggiornare il carattere:

- (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

Grazie, molto utile. La terza riga del metodo dovrebbe essere 'Intervallo NSRange = NSMakeRange (0, attributeString.length);' per coprire l'intero testo. –

Problemi correlati