在行尾的UITextView点击不应该在下一行返回单词

时间:2013-07-08 15:30:58

标签: ios objective-c uikit uitextview

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

This post帮助我了解了如何识别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中的特定单词是否有更好的方法?

1 个答案:

答案 0 :(得分: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]);
    }
}