[英]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.