更改字体大小而不更改 UITextView attributedText

Change font size without Change UITextView attributedText

我尝试更改我的 UITextView 中的字体大小,每次我更改 attributedText 都会恢复为默认值。

有了这个我把中间测试加粗了:

str = [[NSMutableAttributedString alloc] initWithAttributedString:string];

[str addAttribute:NSFontAttributeName value:newFont range:NSMakeRange(range.location, range.length)];

之前:中间是粗体。

之后:所有文本加粗

我希望在尺寸改变后,粗体保持原样。

编辑:

我尝试了这两种方式:

1)

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:currentTextViewEdit.text];
        [attributedString addAttribute:NSFontAttributeName  value:[UIFont systemFontOfSize:textSize] range:NSMakeRange(0, currentTextViewEdit.text.length)];
        currentTextViewEdit.attributedText = attributedString;

2)

currentTextViewEdit.font = [UIFont   fontWithName:currentTextViewEdit.font.fontName size:textSize];

不清楚你的问题是什么。但是,您的观察 完全正确:如果您使用的是属性文本 (attributedText),那么如果您更改文本视图的纯文本功能(如 font), 它重置属性文本。那是因为你不应该那样做。您不得 尝试将属性文本功能与纯文本功能结合使用。仅当您使用纯文本 text.

时才使用纯文本功能(如 font

例如,如果您想在使用属性文本时更改字体,请更改属性文本的字体。为此,拉出 attributedText,将其放入 NSMutableAttributedString,进行更改,然后将其分配回 attributedText.

据@matt 报道:
aUITextView.font => 更改 text 属性(纯文本)
因此,像您一样在 attributedTexttext 之间切换是导致问题的原因。

关于你的其他解决方案:
加粗效果在NSFontAttributeName里面,就是Font的值。因此,如果您将其替换为普通字体,则会消除 "bold" 效果。斜体也一样。

所以一种方法(未测试,根据您的说法它正在工作):
• 保存 attributedText(记住 "effects",在您的情况下为粗体)
• 保存光标位置(我没有测试,所以我不知道之后光标会去哪里)
• 将字体大小更改为属性字符串
,保持以前的字体(可能是普通的粗体) • 更新 attributedText
• 替换游标

您可以在 UITextView 上使用带有方法 -(void)changeFontSize:(float)newFontSize; 的类别,然后调用 self 而不是 currentTextViewEdit

NSMutableAttributedString *attributedString = [[currentTextViewEdit attributedText] mutableCopy];

//Save the cursor/selection
NSRange cursorRange = [currentTextViewEdit selectedRange];

//Apply to update the effects on new text typed by user?
[currentTextViewEdit setFont:[UIFont fontWithName:[[currentTextViewEdit font] fontName] size:newFontSize]];

//Update the font size
[attributedString enumerateAttribute:NSFontAttributeName
                             inRange:NSMakeRange(0, [attributedString length])
                             options:0
                          usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
                              UIFont *currentfont = (UIFont*)value;
                              UIFont *newFont = [UIFont fontWithName:[currentfont fontName] size:newFontSize];
                              [attributedString addAttribute:NSFontAttributeName value:newFont range:range];
                          }];
[currentTextViewEdit setAttributedText:attributedString];

//To restaure the cursor/selection
[currentTextViewEdit setSelectedRange:cursorRange];