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

时间:2013-07-10 05:29:52

标签: ios uitextview 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;

}

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

提前致谢。

1 个答案:

答案 0 :(得分:0)

您不应将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;
}