美文网首页
iOS 屏幕取词(OC 、 swift)

iOS 屏幕取词(OC 、 swift)

作者: 假如兔子失了尾 | 来源:发表于2022-08-31 09:41 被阅读0次

    功能:屏幕取词,从点击屏幕的位置获取范围内的单个单词
    实现:使用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)

          本文链接:https://www.haomeiwen.com/subject/bpgjnrtx.html