在iOS中的UITextView的选定文本上应用富文本格式

Sha*_*eri 7 uitextview ios nsmutableattributedstring

我正在创建一个应用程序,我必须实现这样的功能:

1)写入textview

2)从textview中选择文本

3)允许用户对所选文本应用粗体,斜体和下划线功能.

我已经开始使用NSMutableAttributedString实现它.它适用于粗体和斜体,但仅使用选定的文本替换textview文本.

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

}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我实现这个功能吗?

提前致谢.

小智 1

您不应该用于didChangeSelection此目的。shouldChangeTextInRange代替使用。

这是因为当您将属性字符串设置为新字符串时,您不会替换特定位置的文本。您可以用新文本替换全文。您需要范围来定位要更改文本的位置。

- (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;
}
Run Code Online (Sandbox Code Playgroud)