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

时间:2017-05-15 09:20:47

标签: ios swift 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

我该怎么做?

1 个答案:

答案 0 :(得分:0)

要检测特定行上的点击(如问题标题所示),则以下代码可以完成此任务:

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

P.S。您的UITextView不应该是可编辑的。