I try to change a font size in my UITextView and every time I change the attributedText was restore to default.
with this I make the middle test bold :
str = [[NSMutableAttributedString alloc] initWithAttributedString:string];
[str addAttribute:NSFontAttributeName value:newFont range:NSMakeRange(range.location, range.length)];
before: that was bold font in the middle.
after :all the text bold
I want that after the size change the bold stay where he be.
Edit :
I try with this two ways :
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];
As reported by @matt:
aUITextView.font
=> change on text
property (plain text)
So switching between attributedText
and text
like you're doing is causing the issue.
On your other solution:
Bold effect is inside the NSFontAttributeName
, it's the Font value. So if you replace it by a common font, that will remove the "bold" effect. Same for italic.
So a way to do it (not tested, by according to you it's working):
• Save the attributedText
(to remember the "effects", like bold in your case)
• Save the cursor position (I didn't test, so I don't know where would go the cursor afterward)
• Change the font size keeping the previous font (may be bold of normal) to the attributed string
• Update the attributedText
• Replace the cursor
You can use a Category on UITextView
with a method -(void)changeFontSize:(float)newFontSize;
and then you call self
instead of 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];