2

I have this code for creating an Attributed String with an image on a UITextView

func setImageOnString(imageName: String) {

    let fullString = NSMutableAttributedString(attributedString: attributedText)
    let imageAttachment = NSTextAttachment()

    imageAttachment.image = #imageLiteral(resourceName: "UncheckedImage")
    imageAttachment.bounds = CGRect(x: 0, y: 0, width: 14, height: 14)

    let image1String = NSAttributedString(attachment: imageAttachment)
    let myCustomAttribute = [ "MyCustomAttributeName": "some value"]

    fullString.append(image1String)
    fullString.addAttributes(myCustomAttribute, range: selectedRange)
    self.attributedText = fullString

}

But then I can't find a way of changing this image when something happen like a touch. The problem isn't the touch, it is changing the image.

dmram
  • 125
  • 1
  • 12
  • Use `enumerateAttribute()` looking for `NSAttachmentAttributeName`, and call `replacingOccurrences(of: with:)` to replace it. See there http://stackoverflow.com/questions/41535726/how-to-detect-if-a-nsattributedstring-contains-a-nstextattachment-and-remove-it (and the comments) – Larme Feb 03 '17 at 12:52

1 Answers1

0

Try This-

Add TapGestureRecognizer in your UILable like below code

  override func viewDidLoad() {
    super.viewDidLoad()
    self.lblText.isUserInteractionEnabled = true
    let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(TouchUIViewController.labelPressed))
    self.lblText.addGestureRecognizer(gestureRecognizer)

    self.lblText.attributedText = self.attributedString("menulogout_normal")

 }

 func labelPressed() {
  self.lblText.attributedText = self.attributedString("menulogout_pressed")

}

And write separate method for creating NSAttributedString -

 func attributedString(_ imageName: String) -> NSAttributedString {

    let fullString = NSMutableAttributedString(string: "Start of text")
    let image1Attachment = NSTextAttachment()
    image1Attachment.image = UIImage(named: imageName)
    let image1String = NSAttributedString(attachment: image1Attachment)
    fullString.append(image1String)
    fullString.append(NSAttributedString(string: "End of text"))
    return fullString
}
Prema Janoti
  • 836
  • 5
  • 18