Applying rich text format for selected text UITextView in iOS

I am creating an application in which I have to implement such functions:

1) Write to text box

2) Select the text from the text box

3) Allow the user to apply bold, italic and underlined functions for the selected text.

I started implementing it using NSMutableAttributedString. It works in bold and italics, but replaces text with only selected text.

-(void) textViewDidChangeSelection:(UITextView *)textView { rangeTxt = textView.selectedRange; selectedTxt = [textView textInRange:textView.selectedTextRange]; NSLog(@"selectedText: %@", selectedTxt); } -(IBAction)btnBold:(id)sender { UIFont *boldFont = [UIFont boldSystemFontOfSize:self.txtNote.font.pointSize]; NSDictionary *boldAttr = [NSDictionary dictionaryWithObject:boldFont forKey:NSFontAttributeName]; NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:selectedTxt attributes:boldAttr]; txtNote.attributedText = attributedText; } 

Can anyone help me implement this functionality?

Thanks in advance.

+6
source share
1 answer

You should not use didChangeSelection for this purpose. Use shouldChangeTextInRange .

This is because when you set the attribute string to a new one, you are not replacing the text of a specific location. You replace the full text with new text. You need a range to find the position in which you want to change the text.

 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ NSMutableAttributedString *textViewText = [[NSMutableAttributedString alloc]initWithAttributedString:textView.attributedText]; NSRange selectedTextRange = [textView selectedRange]; NSString *selectedString = [textView textInRange:textView.selectedTextRange]; //lets say you always want to make selected text bold UIFont *boldFont = [UIFont boldSystemFontOfSize:self.txtNote.font.pointSize]; NSDictionary *boldAttr = [NSDictionary dictionaryWithObject:boldFont forKey:NSFontAttributeName]; NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:selectedString attributes:boldAttr]; // txtNote.attributedText = attributedText; //don't do this [textViewText replaceCharactersInRange:range withAttributedString:attributedText]; // do this textView.attributedText = textViewText; return false; } 
0
source

Source: https://habr.com/ru/post/949079/


All Articles