2012-07-05 144 views
5
的搭話從長按字

現在我已經發現長按中的UITextView現在中的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); 
    } 

,我應該怎麼做才能讓字其中有長按的內容,並獲得一個矩形準備展示PopOver的單詞?

+0

請檢查http://stackoverflow.com/questions/8811909/getting-the-word-touched-in-a-uilabel-uitextview/21577829#21577829。我已經使用過'UITapGestureRecognizer',你可以用'UILongPressGestureRecognizer'替換它。 – TheTiger 2014-02-05 12:54:58

回答

15

該函數將返回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

您可能想要查看文本視圖的'tokenizer'屬性的'rangeEnclosingPosition:withGranularity:inDirection:'方法。 – 2012-07-12 00:04:35

+0

謝謝搶劫,這讓它更簡單!我編輯了答案以包含您的建議。 – cayeric 2012-07-12 07:44:41

+0

有沒有辦法做到這一點倒退得像一個單詞的位置? – Sirens 2012-07-21 21:18:46