Adina Marin
Adina Marin

Reputation: 663

Edit text view attributes

I have a text view and i want to be able to make a selection of a sentece and to change the size / color / font only for the selected part .

I did this part to take the selected word:

-(void)textViewDidChangeSelection:(UITextView *)textView{

    UITextRange *selectedRange = [textView selectedTextRange];
    NSString *selectedText = [textView textInRange:selectedRange];
    }

but i don't know how to make changes and also to change the color of selection part.

Any help will be apreciate . Thanks in advance.

Upvotes: 2

Views: 286

Answers (2)

Jamil
Jamil

Reputation: 2999

It is better by adding a NSDictionay as attribute text.

-(void)textViewDidChangeSelection:(UITextView *)textView{
UITextRange *selectedRange = [textView selectedTextRange];
NSString *selectedText = [textView textInRange:selectedRange];
 NSLog(@"selectedText:%@",selectedText);

if (selectedText.length) {
    UIColor *color = [UIColor redColor];
    UIFont *font = [UIFont fontWithName:@"Arial" size:30.0];
    NSDictionary *attrs = @{NSForegroundColorAttributeName : color,NSFontAttributeName:font};//
    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];
    [attrStr addAttributes:attrs range:[textView.text rangeOfString:selectedText]];
     myColoredTextview.attributedText = attrStr;
}

}

Upvotes: 2

tuledev
tuledev

Reputation: 10317

You can change color, or something of a text like this:

  NSMutableAttributedString * atBody = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];

  [atBody addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[textView.text rangeOfString:selectedString]];

  textView.attributedText = atBody;

Upvotes: 3

Related Questions