如何解析UITextView的.attributedText以区分粘贴的图像和常规文本?

时间:2016-08-20 22:19:36

标签: ios swift uitextview nsattributedstring

我有一个处理粘贴图像的功能,我正在尝试使用我的服务器来处理它们,就像iMessage一样:在粘贴图像之前和之后为文本分别添加消息。

这是我将图像添加到textView的代码。

override func didPasteMediaContent(userInfo: [NSObject : AnyObject]) {
    if let pickedImage = UIPasteboard.generalPasteboard().image {
        // Image Caching
        if let data = UIImageJPEGRepresentation(pickedImage, 0.50) {
            hanekeCount += 1
            haneke.set(value: data, key: "pastedImage\(hanekeCount)")
        }

        // Image resizing
        let textViewWidth: CGFloat = self.textView.frame.size.width - 20
        let percentResize = textViewWidth / pickedImage.size.width
        let toBeExportedHeight = pickedImage.size.height * percentResize
        let resizedImage = ImageManipulationManager.sharedInstance.resizeImage(exportedWidth: Int(textViewWidth),exportedHeight: Int(toBeExportedHeight), originalImage: pickedImage)

        // Storage into TextView
        let attributedString = NSAttributedString(string: textView.text)
        let attachment = NSTextAttachment()
        attachment.image = resizedImage
        let attString = NSAttributedString(attachment: attachment)
        print(textView.selectedRange.location)
        textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location)
        textView.selectedRange.location = textView.selectedRange.location + 1
        textView.textStorage.insertAttributedString(NSAttributedString(string: "\n"), atIndex: textView.selectedRange.location)
        textView.selectedRange.location = textView.selectedRange.location + 1
        textView.font = UIFont.systemFontOfSize(16.0)
    }
}

0 个答案:

没有答案