2

我试图在 UITextView (不可编辑)中对特定单词进行点击 - 想象一下 Instagram 或 Twitter 移动应用程序中的主题标签或提及。

这篇文章帮助我了解了如何识别 UITextView 中特定单词的点击:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self     action:@selector(printWordSelected:)];
    [self.textView addGestureRecognizer:tap];
}

- (IBAction)printWordSelected:(id)sender
{
    NSLog(@"Clicked");

    CGPoint pos = [sender locationInView:self.textView];
    NSLog(@"Tap Gesture Coordinates: %.2f %.2f", pos.x, pos.y);

    //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:UITextGranularityWord
                                                           inDirection:UITextLayoutDirectionRight];

    NSLog(@"WORD: %@", [self.textView textInRange:wr]);
} 

不幸的是,这种方法不是防弹的,并且将在行尾的空白处的点击报告为对下一行开头的单词的点击。

显然,这是 UITextView 中自动换行的结果,有时会将单词移动到下一行的开头。

  1. 有没有办法解决它,而不是将这些点击在行尾报告为点击包装词?
  2. 是否有更好的方法来继续用户点击 UITextView 中的特定单词?
4

1 回答 1

2

一个简单的解决方案是只返回两个方向(左右)都相同的单词。然而,这种方法有一个限制。您将无法选择单个字符的单词。

- (IBAction)printWordSelected:(id)sender
{
    CGPoint pos = [sender 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:UITextGranularityWord
                                                           inDirection:UITextLayoutDirectionRight];

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


    if ([wr isEqual:wl]) {

        NSLog(@"WORD: %@", [self.textView textInRange:wr]);
    }
} 
于 2013-07-08T16:42:28.147 回答