获取点击UITextView的range

- (void)viewDidLoad {
    [super viewDidLoad];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(textViewTapped:)];
    tap.delegate = self; 
    tap.numberOfTapsRequired = 1; 
   [self.textView addGestureRecognizer:tap];
}   

- (void)textTapped:(UITapGestureRecognizer *)recognizer
{
    UITextView *textView = (UITextView *)recognizer.view;

    // Location of the tap in text-container coordinates

    NSLayoutManager *layoutManager = textView.layoutManager;
    CGPoint location = [recognizer locationInView:textView];
    location.x -= textView.textContainerInset.left;
    location.y -= textView.textContainerInset.top;

    // Find the character that's been tapped on

    NSUInteger characterIndex;
    characterIndex = [layoutManager characterIndexForPoint:location
                                           inTextContainer:textView.textContainer
                  fractionOfDistanceBetweenInsertionPoints:NULL];

    // 设置点击的光标
    [label setSelectedRange:NSMakeRange(characterIndex, 0)];
//    if (characterIndex < textView.textStorage.length) {
//
//        NSRange range;
//        id value = [textView.attributedText attribute:string atIndex:characterIndex effectiveRange:&range];
//
//        // Handle as required...
//
//        DEBUGLOG(@"%@, %lu, %d", value, (unsigned long)range.location, range.length);
//
//    }
}


#pragma mark - Gesture recognizer delegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES; 
}

别忘了实现PS: Don't forget < UIGestureRecognizerDelegate >
参考:https://stackoverflow.com/questions/28858908/add-uitapgesturerecognizer-to-uitextview-without-blocking-textview-touches

你可能感兴趣的:(获取点击UITextView的range)