2017-02-03 21 views
0

У меня есть этот код для создания ПРИСВОЕНА Строка с изображением на UITextViewИзмените образ выбранного NSAttributedString

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 

} 

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

+0

Используйте 'enumerateAttribute()' 'ищет NSAttachmentAttributeName 'и вызовите' replacingOccurrences (of: with:) 'для его замены. См. Там http://stackoverflow.com/questions/41535726/how-to-detect-if-a-nsattributedstring-contains-a-nstextattachment-and-remove-it (и комментарии) – Larme

ответ

0

Попробуйте this-

Добавить 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 
}