How to detect if a NSAttributedString contains a NSTextAttachment and remove it?

五迷三道 提交于 2019-12-03 17:14:48

Swift 4, XCode 9 answer:

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)

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!