How to detect touch on NSTextAttachment

前端 未结 7 907
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 03:24

What is the best way to detect when user taps on NSTextAttachment on iOS?

I think that one of the ways would be checking for the character on carret\'s

7条回答
  •  孤城傲影
    2020-12-14 03:40

    SWIFT 4.2

    @objc func myMethodToHandleTap(_ sender: UITapGestureRecognizer) {
    
    let myTextView = sender.view as! UITextView
    
         let layoutManager = myTextView.layoutManager
    
         // location of tap in myTextView coordinates and taking the inset into account
         var location = sender.location(in: myTextView)
         location.x -= myTextView.textContainerInset.left;
         location.y -= myTextView.textContainerInset.top;
    
         // character index at tap location
         let characterIndex = layoutManager.characterIndex(for: location, in: myTextView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
    
         if characterIndex < myTextView.textStorage.length {
    
            let attributeValue = myTextView.attributedText.attribute(NSAttributedString.Key.attachment, at: characterIndex, effectiveRange: nil) as? NSTextAttachment
    
            if let _ = attributeValue {
               print("TAPPED ATTACHMENT")  
            }
         }
    
    }
    

提交回复
热议问题