5

NSAttributedStringとして添付された画像を含む可能性のある a を入力として受け取ります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に複数の添付ファイルが含まれている場合( にいくつか表示\u{ef}されますstring)、列挙が条件にif (value as? NSTextAttachment) != nil数回一致すると予想していましたが、そのコード ブロックは 1 回しか実行されません。

すべての添付ファイルを削除するにはどうすればよいですか?

4

1 に答える 1

7

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)

}
于 2017-10-03T05:16:42.553 に答える