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

簡単な解決策は、単語が両方向 (左と右) で同じである場合にのみ単語を返すことです。ただし、このアプローチには 1 つの制限があります。1 文字の単語を選択することはできません。

- (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 に答える