Apply rich text format on selected text of UITextView in iOS

后端 未结 1 1999
无人及你
无人及你 2021-02-06 09:02

I am creating an app in which i have to implement functionality like this:

1) Write into textview

2) Select text from textview

3) Allow user to apply bol

1条回答
  •  伪装坚强ぢ
    2021-02-06 09:40

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

    This is because when you set the attributed string to new one you don't replace the text of certain location. You replace full text with your new text. You need range to locate the position where you want the text changed.

    - (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 讨论(0)
提交回复
热议问题