Apply rich text format on selected text of UITextView in iOS

淺唱寂寞╮ 提交于 2019-12-04 09:33:47

问题


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 bold,italic and underline functionality on selected text.

I have started implementing it using NSMutableAttributedString. It's working for bold and italic but replaces the textview 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 anybody please help me out to implement this functionality?

Thanks in advance.


回答1:


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;
}


来源:https://stackoverflow.com/questions/17563046/apply-rich-text-format-on-selected-text-of-uitextview-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!