Изменить изображение выбранной строки NSAttributedString

У меня есть этот код для создания атрибутивной строки с изображением в 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

}

Но тогда я не могу найти способ изменить это изображение, когда что-то происходит, например, прикосновение. Проблема не в прикосновении, а в смене изображения.


person dmram    schedule 03.02.2017    source источник
comment
Используйте enumerateAttribute() для поиска NSAttachmentAttributeName и вызовите replacingOccurrences(of: with:) для его замены. См. там stackoverflow.com/questions/41535726/ (и комментарии)   -  person Larme    schedule 03.02.2017


Ответы (1)


Попробуй это-

Добавьте TapGestureRecognizer в свой UILable, как показано ниже.

  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")

}

И написать отдельный метод для создания 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
}
person Prema Janoti    schedule 03.02.2017