簡體   English   中英

如何檢測NSAttributedString是否包含NSTextAttachment並將其刪除?

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

我收到一個NSAttributedString作為輸入,可能包含附加為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)

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM