UITextView如何获取点击的文字

高亮显示单词

需求:获取点击 UITextView 的某个单词,高亮显示。

思路:创建 textView 的子类。先获取 touchPoint,然后用 textView.layoutManager 的 characterIndexForPoint: 方法获取点击的字符的位置,从位置向前后遍历直到遇到空格就能获取点击的单词的 NSRange,有了 range 就能获取点击的单词,或者高亮显示。

参考:https://stackoverflow.com/questions/19332283/detecting-taps-on-attributed-text-in-a-uitextview-in-ios

子类关键代码:

// WordTextView.m,继承自 UITextView。

// 重写触摸开始函数
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // 获取当前触摸位置的字符所属的字母(提示:触摸位置需向下调整10个点,以便与文本元素对齐)
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    touchPoint.y -= 10;
    
    // 获取点击的字母的位置
    NSInteger characterIndex = [self.layoutManager characterIndexForPoint:touchPoint inTextContainer:self.textContainer fractionOfDistanceBetweenInsertionPoints:NULL];

    // 获取单词的范围。range 由起始位置和长度构成。
    NSRange range = [self getWordRange:characterIndex];
    
    // 高亮单词
    [self modifyAttributeInRange:range];
    
    //调用父类的方法
    [super touchesBegan: touches withEvent: event];
}
//获取单词的范围
- (NSRange)getWordRange:(NSInteger)characterIndex {
    NSInteger left = characterIndex - 1;
    NSInteger right = characterIndex + 1;
    NSInteger length = 0;
    NSString *string = self.attributedText.string;
    
    // 往左遍历直到空格
    while (left >=0) {
        NSString *s=[string substringWithRange:NSMakeRange(left, 1)];
        
        if ([self isLetter:s]) {
            left --;
        } else {
            break;
        }
    }
    
    // 往右遍历直到空格
    while (right < self.text.length) {
        NSString *s=[string substringWithRange:NSMakeRange(right, 1)];
        
        if ([self isLetter:s]) {
            right ++;
        } else {
            break;
        }
    }

    // 此时 left 和 right 都指向空格
    left ++;
    right --;
    NSLog(@"letf = %ld, right = %ld",left,right);

    length = right - left + 1;
    NSRange range = NSMakeRange(left, length);
    
    return range;
}

子类其他代码:

//判断是否字母
- (BOOL)isLetter:(NSString *)str {
    char letter = [str characterAtIndex:0];
    
    if ((letter >= 'a' && letter <='z') || (letter >= 'A' && letter <= 'Z')) {
        return YES;
    }
    return NO;
}

//修改属性字符串
- (void)modifyAttributeInRange:(NSRange)range {
    NSString *string = self.attributedText.string;
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc]initWithString:string attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18]}];

    //添加文字颜色
    [attString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    //添加文字背景颜色
    [attString addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:range];

    self.attributedText = attString;
}

测试代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGRect frame = CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 200);
    WordTextView *textView = [[WordTextView alloc]initWithFrame:frame];
    textView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:textView];

    NSString *string = @"The UIFont class provides the interface for getting and setting font information. The class provides you with access to the font’s characteristics and also provides the system with access to the font’s glyph information, which is used during layout. You use font objects by passing them to methods that accept them as a parameter.";
    NSAttributedString *attrStr = [[NSAttributedString alloc]initWithString:string attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18]}];
    textView.attributedText = attrStr;
}

除了通过继承实现,也可以给 textView 添加手势来实现。
如果有更好的方法,求分享。


<p>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容