2017-02-03 5 views
0

ich diesen Code haben auf einem UITextView ein Zugeschrieben String mit einem Bild für die Erstellung vonein Ändern Sie das Bild von NSAttributedString ausgewählt

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 

} 

Aber dann Ich kann keinen Weg finden, dieses Bild zu verändern, wenn etwas wie eine Berührung geschieht. Das Problem ist nicht die Berührung, es verändert das Bild.

+0

Verwenden 'enumerateAttribute()' Suche 'NSAttachmentAttributeName ', und rufe' explaceOccurrences (of: with:) 'auf, um es zu ersetzen. Siehe dort http://stackoverflow.com/questions/41535726/how-to-detect-if-a-nsattributedstring-contains-a-nntextattachment-and-remove-it (und die Kommentare) – Larme

Antwort

0

Versuchen this-

hinzufügen TapGestureRecognizer in Ihrem UILable wie unten 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") 

} 

Und separate Methode schreiben NSAttributedString für die Erstellung -

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 
} 
Verwandte Themen