更改所选NSAttributedString的图像

时间:2017-02-03 03:46:58

标签: swift image nsmutableattributedstring

我有这个代码用于在UITextView上创建带有图像的Attributed String

  

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

}

但是,当触摸发生某些事情时,我无法找到改变这种形象的方法。问题不在于触摸,而是在改变图像。

1 个答案:

答案 0 :(得分:0)

试试这个 -

在您的UILable中添加TapGestureRecognizer,如下面的代码

  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
}