如何在uitextview或uiimage中突出显示特定句子

时间:2014-03-04 11:37:53

标签: ios iphone objective-c uitouch tap

我想在点击时选择特定句子。我有段落由许多句子组成,每个句子都有一个索引,当我点击它时,我必须显示并突出显示整个句子(诗句)。我已经提取了所需的NSString以突出显示如下:

CGPoint pos = [tap locationInView:self.textView];

//get location in text from textposition at point
UITextPosition *tapPos = [self.textView closestPositionToPoint:pos];

//fetch the word at this position (or nil, if not available)
UITextRange * wr = 
  [self.textView.tokenizer rangeEnclosingPosition:tapPos
                                  withGranularity:UITextGranularitySentence
                                      inDirection:UITextLayoutDirectionRight];

//fetch the word at this position (or nil, if not available)
UITextRange * wl = 
  [self.textView.tokenizer rangeEnclosingPosition:tapPos
                                  withGranularity:UITextGranularitySentence
                                      inDirection:UITextLayoutDirectionLeft];

if ([wr isEqual:wl]) {

    NSLog(@"WORD: %@", [self.textView textInRange:wr]);       
    NSString *infoString = [self.textView textInRange:wr];
    NSMutableAttributedString *attString =
      [[NSMutableAttributedString alloc] initWithString:infoString];
    NSInteger _stringLength = [infoString length];

    UIColor *_black = [UIColor blackColor];
    UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" 
                                   size:30.0f];
    [attString addAttribute:NSFontAttributeName 
                      value:font 
                      range:NSMakeRange(0, _stringLength)];
    [attString addAttribute:NSForegroundColorAttributeName 
                      value:_black 
                      range:NSMakeRange(0, _stringLength)];
}

1 个答案:

答案 0 :(得分:0)

请查看:https://github.com/00StevenG/UITextViewExtras

希望,这对你有帮助,

:)