若要在 iOS 的 UITextView 中实现文字点击的功能,可以使用 UITapGestureRecognizer 来监听点击事件,并通过 UITextPosition 来获取点击位置的文字索引。

以下是一个示例的 Objective-C 代码:

首先,需要为 UITextView 添加一个 UITapGestureRecognizer:

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[yourTextView addGestureRecognizer:tapGestureRecognizer];

接下来,实现 handleTap 方法来处理点击事件:

- (void)handleTap:(UITapGestureRecognizer *)tapGestureRecognizer {
    UITextView *textView = (UITextView *)tapGestureRecognizer.view;
    
    CGPoint tapLocation = [tapGestureRecognizer locationInView:textView];
    
    UITextPosition *textPosition = [textView closestPositionToPoint:tapLocation];
    UITextRange *textRange = [textView.tokenizer rangeEnclosingPosition:textPosition withGranularity:UITextGranularityWord inDirection:UITextStorageDirectionForward];
    
    NSString *tappedWord = [textView textInRange:textRange];
    
    NSLog('Tapped word: %@', tappedWord);
    
    // 在这里处理点击事件,例如弹出一个 UIAlertController 显示点击的文字
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:'Tapped Word' message:tappedWord preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:'OK' style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

上述代码中,我们通过 UITapGestureRecognizer 的 locationInView 方法获取点击位置的坐标,然后使用 UITextView 的 closestPositionToPoint 方法获取最接近点击位置的文字位置,再使用 UITextView 的 tokenizer 的 rangeEnclosingPosition 方法获取包含该位置的文字范围,最后使用 UITextView 的 textInRange 方法获取被点击的文字。

你可以根据需要在 handleTap 方法中自定义处理点击事件的逻辑。

iOS UITextView 文字点击事件实现 - Objective-C 代码示例

原文地址: https://www.cveoy.top/t/topic/o8kK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录