bya*_*abe 14 text-styling nsattributedstring dynamic-text ios7
我在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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2687 次 |
| 最近记录: |