簡體   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