2013-09-21 10 views
14

Mam NSAttributedString w UITextView i chciałbym obsłużyć UIContentSizeCategoryDidChangeNotification podczas pracy z typem dynamicznym, a zwłaszcza stylów tekstu. Wszystkie przykłady, które widziałem (IntroToTextKitDemo) odnoszą się do przypadku, w którym czcionka jest taka sama dla całego elementu interfejsu użytkownika. Czy ktokolwiek wie, jak poprawnie obsłużyć to, aby wszystkie atrybuty zaktualizować poprawnie?Obsługa UIContentSizeCategoryDidChangeNotification dla NSAttributedString w UITextView

Uwaga: Pytałem o to na forach programistów, gdy iOS 7 był pod NDA. Zamieszczam to tutaj, ponieważ znalazłem rozwiązanie i uważałem, że inni mogą uznać to za przydatne.

Odpowiedz

9

Znalazłem rozwiązanie. Podczas obsługi powiadomienia należy przejść do atrybutów i wyszukać style tekstowe oraz zaktualizować czcionkę:

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

Dzięki, bardzo przydatne. Trzecia linia metody powinna być 'NSRange range = NSMakeRange (0, attributedString.length);' na pokrycie całego tekstu. –

Powiązane problemy