UITextView如何获取点击的文字

UITextView如何获取点击的文字_第1张图片
高亮显示单词

需求:获取点击 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 添加手势来实现。
如果有更好的方法,求分享。


你可能感兴趣的:(UITextView如何获取点击的文字)