2012-07-05 13 views
5

Ora ho già rilevato lungo tap in UITextViewGet parola lungo tap in una parola di UITextView

- (void)viewDidLoad 
    { 
     [super viewDidLoad]; 
     UILongPressGestureRecognizer *LongPressgesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressFrom:)];  
     [[self textview] addGestureRecognizer:LongPressgesture]; 
     longPressGestureRecognizer.delegate = self; 
    } 
    - (void) handleLongPressFrom: (UISwipeGestureRecognizer *)recognizer 
    { 
     CGPoint location = [recognizer locationInView:self.view]; 

     NSLog(@"Tap Gesture Coordinates: %.2f %.2f", location.x, location.y); 
    } 

Ora, come devo fare per ottenere contenuti di parola che ha premuto a lungo, e ottenere un rettangolo di che parola da preparare per mostrare il PopOver?

+0

Si prega di verificare http://stackoverflow.com/questions/8811909/getting-the-word-touched-in-a-uilabel-uitextview/21577829#21577829. Ho usato 'UITapGestureRecognizer' puoi sostituirlo con' UILongPressGestureRecognizer'. – TheTiger

risposta

15

Questa funzione restituirà la parola in una determinata posizione in un UITextView.

+(NSString*)getWordAtPosition:(CGPoint)pos inTextView:(UITextView*)_tv 
{ 
    //eliminate scroll offset 
    pos.y += _tv.contentOffset.y; 

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

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

    return [_tv textInRange:wr]; 
} 
+1

Si potrebbe voler controllare il metodo 'rangeEnclosingPosition: withGranularity: inDirection:' della proprietà 'tokenizer' della vista testo. –

+0

Grazie a te, questo lo rende molto più semplice! Ho modificato la risposta per includere il tuo suggerimento. – cayeric

+0

C'è un modo per fare questo all'indietro come ottenere la posizione di una parola? – Sirens

Problemi correlati