首页 > 解决方案 > UITextView 延迟 AttributedString 链接 SwiftUI

问题描述

我有一个看起来像这样的文本视图:

class StudyText: UITextView,  UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print(URL)

        return false
    }

    override var canBecomeFirstResponder: Bool {
        return false
    }
}

这是结构:

struct ClickableText: UIViewRepresentable {
    @Binding var text: NSMutableAttributedString

    func makeUIView(context: Context) -> StudyText {
        let view = StudyText()

        view.dataDetectorTypes = .all
        view.isEditable        = false
        view.isSelectable      = true
        view.delegate          = view
        view.isUserInteractionEnabled = true

        return view
    }

    func updateUIView(_ uiView: StudyText, context: Context) {
        uiView.attributedText = text

    }

}

我正在使用属性链接。

我尝试的每个解决方案都不会使链接响应快速点击。立即地。在显示打印语句之前需要一些延迟。

我试过这个:

view.delaysContentTouches = false

我试过这个:

let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tappedTextView(tapGesture:)))
self.addGestureRecognizer(tapRecognizer)


@objc func tappedTextView(tapGesture: UIGestureRecognizer) {

    let textView = tapGesture.view as! UITextView
    let tapLocation = tapGesture.location(in: textView)
    let textPosition = textView.closestPosition(to: tapLocation)
    let attr = textView.textStyling(at: textPosition!, in: .forward)!

    if let url: URL = attr[NSAttributedString.Key(rawValue: NSAttributedString.Key.link.rawValue)] as? URL {
        print("clicking here: \(url)")

    }

}

但他们都没有工作。它总是延迟响应我该如何解决这个问题?

标签: iosswiftswiftuiuitextviewuiviewrepresentable

解决方案


UITextView响应单击手势(可让您点击链接)和双击手势(可让您选择文本)。在您点击链接一次后,您是否已完成手势或是否即将进行第二次点击尚不清楚。只有在没有第二次点击的短暂延迟之后,才能确定您实际上是在执行一次点击时才textView(_:shouldInteractWith:in:interaction:)调用该点。

不幸的是,没有标准的方法可以在UITextView不允许文本选择的情况下允许跟随链接。您也许可以搜索在视图上注册的手势识别器,找到负责识别双击并禁用它的手势识别器,但这样做可能会产生意想不到的副作用。


推荐阅读