2012-07-05 31 views
5

Bây giờ tôi đã phát hiện vòi dài trong UITextViewNhận lời từ vòi dài trong một từ của 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); 
    } 

Bây giờ, Làm thế nào tôi nên làm gì để có được nội dung của từ đó có báo chí dài, và có được một rect đó từ để chuẩn bị cho thấy PopOver?

+0

Vui lòng kiểm tra http://stackoverflow.com/questions/8811909/getting-the-word-touched-in-a-uilabel-uitextview/21577829#21577829. Tôi đã sử dụng 'UITapGestureRecognizer', bạn có thể thay thế nó bằng' UILongPressGestureRecognizer'. – TheTiger

Trả lời

15

Hàm này sẽ trả về từ tại một vị trí nhất định trong 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

Bạn có thể muốn kiểm tra phương thức 'rangeEnclosingPosition: withGranularity: inDirection:' của thuộc tính 'tokenizer' của khung nhìn văn bản. –

+0

Cảm ơn bạn cướp, mà làm cho nó đơn giản hơn nhiều! Tôi đã chỉnh sửa câu trả lời để bao gồm đề xuất của bạn. – cayeric

+0

Có cách nào để làm điều này ngược lại như nhận vị trí của một từ không? – Sirens

Các vấn đề liên quan