2017-01-08 17 views
0

NSAttributedStringには、NSTextAttachmentとして添付された画像が含まれている可能性があります。実際にそのような画像が添付されているかどうかを確認し、そのような場合は削除する必要があります。私は成功していない関連記事を探していましたが、どうすればこのことができますか?NSAttributedStringにNSTextAttachmentが含まれているかどうかを検出して削除するにはどうすればよいですか?

EDIT:は、私はこれをしようとしている:

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数回に一致するように列挙を期待そのコードブロックは一度だけ実行されます。

どのようにすべての添付ファイルを削除できますか?

+0

あなたが任意の添付ファイルの文字を検索し、削除することもできます:https://developer.apple.com/reference/uikit/nstextattachment/1508411-attachment_character – MathewS

+1

列挙'NSAttachmentAttributeName'のattributedStringを削除して削除します。ここでは、コードを見ることができます:http://stackoverflow.com/questions/29152660/extract-uiimage-from-nsattributed-string/29153172#29153172 – Larme

+0

@MathewSありがとう、どのような文字を列挙する最も適切な方法は、 'NSAttachmentCharacter'が存在するかどうかを調べるNSAttributedString'? – AppsDev

答えて

0

スウィフト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) 

} 
関連する問題