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

7

我正在开发一个应用程序,需要实现以下功能:

1) 在文本视图中写入

2) 从文本视图中选择文本

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

我已经开始使用NSMutableAttributedString来实现它。这对于加粗和斜体有用,但是只替换了文本视图的选定文本。

-(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
这是内置于 UITextView 中的(自 iOS 6.0 起)。将 allowsEditingTextAttributes 属性设置为 YES - rmaddy
我已经完成了这个。我的问题只是在textview中,选定的加粗/斜体文本仍然存在,而其他文本已被删除。我想要替换textview文本中仅选定的加粗/斜体文本。 - Shah Paneri
3
通过启用“allowsEditingTextAttributes”属性,您无需使用您发布的任何代码。如果您在文本视图中选择一些文本,则文本视图会自动提供BUI(加粗/斜体/下划线)菜单选项。您不需要编写任何代码来实现这一点。 - rmaddy
不行,它不允许我这样做。我已经在viewDidLoad方法中写了txtNote.allowsEditingTextAttributes = YES;,但它和之前一样。 - Shah Paneri
“Same as before”是什么意思?这对我有效。设置该属性后,当在文本视图中选择文本时,我会看到新的格式菜单。在尝试设置属性时,请确保txtNote不为nil - rmaddy
是的。当选择文本时,它会显示加粗、斜体和下划线选项。非常感谢。 :) - Shah Paneri
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接