gpt4 book ai didi

ios7 - 处理 UITextView 中 NSAttributedString 的 UIContentSizeCategoryDidChangeNotification

转载 作者:行者123 更新时间:2023-12-03 22:34:43 30 4
gpt4 key购买 nike

我在 UITextView 中有一个 NSAttributedString,并且希望在使用动态类型特别是文本样式时处理 UIContentSizeCategoryDidChangeNotification。我见过的所有示例(IntroToTextKitDemo)都解决了整个 UI 元素的字体相同的情况。有谁知道如何正确处理这个问题,以便所有属性都能正确更新?

注意:当 iOS 7 处于保密协议(protocol)下时,我在开发者论坛上问过这个问题。我在这里发布它是因为我找到了一个解决方案并认为其他人可能会觉得它有用。

最佳答案

我找到了解决方案。处理通知时,您需要遍历属性并查找文本样式并更新字体:

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

关于ios7 - 处理 UITextView 中 NSAttributedString 的 UIContentSizeCategoryDidChangeNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928620/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com