Swift NSTextAttachment with Tap recognition inside TextView

198 Views Asked by At

Problem:

How can I recognize tap recognition on a NSTextAttachment?

I have a image attachment that is appended to the end of an AttributedString on a textView inside a tableView cell.

How can I add a tap gesture ONLY to the attachment itself?

Code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ChatTableViewCell", for: indexPath) as! ChatTableViewCell
        let attachment = messageData[indexPath.row].attachment
          
            let attributedText = NSMutableAttributedString()
            let attributedText2 = NSMutableAttributedString(string: messageData[indexPath.row].message + "\n\n")
            
            attributedText2.append(NSAttributedString(attachment: attachment))
            attributedText2.append(attributedText)
            cell.chatTextView.attributedText = attributedText2

            return cell  
    }

PSEUDO:

attachment.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap(recognizer:))))

Other notes:

I can add a gesture recognizer to the textView, or text in the textview. Im just not sure how to add a tap gesture specifically to the attachment itself.

Platform:

-iOS, Swift

1

There are 1 best solutions below

1
Akshay Sharma On

I think you have to set "add gesture recognizer"

cell.chatTextView.tag = indexPath.row cell.chatTextView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap(recognizer:))))

and make sure you have set the tag before the add tap gesture.