UITextView - 修改所选文本

时间:2011-07-06 15:19:48

标签: iphone uitextview

我有一个UITextView,我想选择此文本的某个部分并修改其样式。比如改变颜色,使其变为斜体或粗体,增加字体大小或更改字体系列。

任何帮助?

3 个答案:

答案 0 :(得分:0)

是。等待iOS 5.我认为关于iOS 5的大部分信息仍然在NDA下,所以我们不能在这里讨论。

或者使用CoreText自行开发。

答案 1 :(得分:0)

您可以使用以下替代方法: -

  • 首先使用滚动视图,使用粗体字或chagne颜色添加不同样式的标签或其他文本视图,并在scrollview中添加为子视图。
  • 对于在scrollview中添加的文本视图,您应该将textview的框架视为textview中的文本或线条,以便在textview中停止滚动,因为我们已经在scrollview中添加了textview以便更好地查看。
  • 因此,根据需要获取尽可能多的文本视图或标签或图像,然后添加到scrollview,使用“界面”构建器可以非常简单地执行此操作。只需要为scrollview定义一个完美的内容大小取决于你拥有的子视图。

答案 2 :(得分:0)

您应该使用shouldChangeTextInRange。这是因为您需要范围来定位您想要更改文本的位置 UITextView可让您在textView.attributedString中保存您的风格 解决方案是获取textView的属性字符串,并用更改或样式化的文本替换其中的所需子字符串。

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

     NSMutableAttributedString *textViewText = [[NSMutableAttributedString alloc]initWithAttributedString:textView.attributedText];   //gets textView style string

     NSRange selectedTextRange = [textView selectedRange];
     NSString *selectedString = [textView textInRange:textView.selectedTextRange]; //our selected text 

    //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]; //make attributed string of our selectedtext

    [textViewText replaceCharactersInRange:range withAttributedString:attributedText]; // replace
    textView.attributedText = textViewText;

    return false;
}
相关问题