2013-07-08 31 views
2

我試圖繼續在UITextView(不可編輯)中的特定單詞上點擊 - 想象在Instagram或Twitter移動應用程序中的主題標籤或提及。UITextView在行尾應該不會返回下一行的文字

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內的特定單詞上點擊?

回答

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]); 
    } 
} 
+0

太棒了!有效! 由於我想在UITextView內部使用它的'特殊'字樣,如標籤和提及(以#和@作爲前綴),因此在單個字符字上丟失不是問題。 –

相關問題