繁体   English   中英

如何在UITextView的特定行上检测点击?

[英]How to detect tap on particular line on UITextView?

我有一个UITextview我想做几个词作为链接,以便我可以检测到它们的点击并获取回调函数。 我已经将UITextView链接属性设置为选中并在下面的委托方法中实现。

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
    print("hello")
    return true
}

@available(iOS 10.0, *)
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    print("bye")
    return true
} 

我还使用NSMutableString将字符串设置为粗体和斜体

let str = NSMutableAttributedString(string: self.tvBottom.text as String, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17.0)])
str.addAttribute(NSLinkAttributeName, value: "http://www.google.com", range: NSRange(location: 4, length: 14))
str.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue , range: NSRange(location: 4, length: 14))
let boldFontAttribute = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 17.0)]
str.addAttributes(boldFontAttribute, range: NSRange(location: 4, length: 14))
str.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 4, length: 14))
self.tvBottom.attributedText = str

我怎样才能做到这一点?

要检测特定行上的轻击(如您的问题的标题所示),那么以下代码即可完成工作:

func didTapTextView(recognizer: UITapGestureRecognizer) {
    if recognizer.state == .recognized {
        let location = recognizer.location(ofTouch: 0, in: textView)

        if location.y >= 0 && location.y <= textView.contentSize.height {
            guard let font = textView.font else {
                return
            }

            let line = Int((location.y - textView.textContainerInset.top) / font.lineHeight) + 1
            print("Line is \(line)")
        }
    }
}

当在我们的textView上检测到轻敲时,下面的代码用于调用上述方法。

let tap = UITapGestureRecognizer(target: self, action: #selector(didTapTextView(recognizer:)))
tap.cancelsTouchesInView = false
textView.addGestureRecognizer(tap)

但是,如果只想检测链接上的点击,则应遵循UITextViewDelegate协议,并实现以下方法:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    return true
}

当然,您需要将委托添加到您的textView中(例如,在viewDidLoad()

textView.delegate = self

PS您的UITextView应该不可编辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM