如何检测NSAttributedString是否包含NSTextAttachment并将其删除?

我收到一个NSAttributedString作为input,它可能包含一个作为NSTextAttachment附加的图像。 我需要检查是否附加了这样的图像,并在这种情况下,删除它。 我一直在寻找相关的职位没有成功,我怎么能这样做?

编辑:我想这个:

 let mutableAttrStr = NSMutableAttributedString(attributedString: textView.attributedText) textView.attributedText.enumerateAttribute(NSAttachmentAttributeName, in: NSMakeRange(0, textView.attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) in if (value as? NSTextAttachment) != nil { mutableAttrStr.replaceCharacters(in: range, with: NSAttributedString(string: "")) } } 

如果textView.attributedText包含多个附件(我在其string看到了几个\u{ef} ),我希望枚举匹配条件if (value as? NSTextAttachment) != nil几次,但是该代码块是只执行一次。

我如何删除所有附件?

Swift 4,XCode 9回答:

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { picker.dismiss(animated: true, completion: nil) guard let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else { return } //check if textview contains any attachment txtView.attributedText.enumerateAttribute(NSAttributedStringKey.attachment, in: NSRange(location: 0, length: txtView.attributedText.length), options: []) { (value, range, stop) in if (value is NSTextAttachment){ let attachment: NSTextAttachment? = (value as? NSTextAttachment) if ((attachment?.image) != nil) { print("1 image attached") let mutableAttr = txtView.attributedText.mutableCopy() as! NSMutableAttributedString //Remove the attachment mutableAttr.replaceCharacters(in: range, with: "") txtView.attributedText = mutableAttr }else{ print("No image attched") } } } //insert only one selected image into TextView at the end let attachment = NSTextAttachment() attachment.image = image let newWidth = txtView.bounds.width - 20 let scale = newWidth / image.size.width let newHeight = image.size.height * scale attachment.bounds = CGRect.init(x: 0, y: 0, width: newWidth, height: newHeight) let attrString = NSAttributedString(attachment: attachment) txtView.textStorage.insert(attrString, at: txtView.selectedRange.location) }