iOS 屏幕取词(OC 、 swift)

功能:屏幕取词,从点击屏幕的位置获取范围内的单个单词
实现:使用UITextView捕获单词

OC

第一步:
关闭textView相应的响应方法

textView.textContainer.lineFragmentPadding = 0.0;
textView.editable = NO;
textView.scrollEnabled = NO;
textView.bounces = NO;
textView.selectable = NO;

第二步:
给textView添加点击事件

UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
[textView addGestureRecognizer:gesture];

第三步:
获取textView相应的点击位置,获取到相应范围内的单词

- (void)tapGesture:(UITapGestureRecognizer *)gesture {
    if (gesture.view == textView && gesture.state == UIGestureRecognizerStateRecognized) {
        CGPoint location = [gesture locationInView:textView];
        UITextPosition *position = [textView closestPositionToPoint:location];
        UITextRange *tapRange = [textView.tokenizer rangeEnclosingPosition:position withGranularity:UITextGranularityWord inDirection:UITextWritingDirectionLeftToRight];
        NSString *word = [textView textInRange:tapRange];
        NSLog(@"点击的单词是:%@",word);
    }
}

swift

第一步:
关闭textView相应的响应方法

textView.textContainer.lineFragmentPadding = 0.0
textView.isEditable = false
textView.isScrollEnabled = false
textView.bounces = false
textView.isSelectable = false

第二步:
给textView添加点击事件

let tap = UITapGestureRecognizer(target: self, action: #selector(tapGesture))
textView.addGestureRecognizer(tap)

第三步:
获取textView相应的点击位置,获取到相应范围内的单词

func tapGesture(tap: UIGestureRecognizer) {
    if tapGR.view == textView && tapGR.state == .recognized {
        let location = tapGR.location(in: textView)
        let position = textView.closestPosition(to: location) ?? UITextPosition.init()
        let tapRange = textView.tokenizer.rangeEnclosingPosition(position, with: .word, inDirection: UITextDirection(rawValue: NSWritingDirection.leftToRight.rawValue))
        if tapRange?.isEmpty == nil {
            print("捕获失败,可能该区域没有单词,或非正确单词")
            return
        }
        let word = textView.text(in: tapRange ?? UITextRange.init()) ?? ""
        print("点击的单词是:"+word)
    }
}

你可能感兴趣的:(iOS 屏幕取词(OC 、 swift))