我根据我在网上找到的内容尝试了很多不同的东西但仍然无法做到这一点。有一些类似的问题,我试图拼凑,但它仍然无法正常工作。以下是我到目前为止的情况:
class CustomUITextView: UITextView {
override func paste(sender: AnyObject?) {
let data: NSData? = UIPasteboard.generalPasteboard().dataForPasteboardType("public.png")
if data != nil {
let attributedString = self.attributedText.mutableCopy() as! NSMutableAttributedString
let textAttachment = NSTextAttachment()
textAttachment.image = UIImage(data: data!)
let attrStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.replaceCharactersInRange(self.selectedRange, withAttributedString: attrStringWithImage)
self.attributedText = attributedString
} else {
let pasteBoard: UIPasteboard = UIPasteboard.generalPasteboard()
let text = NSAttributedString(string: pasteBoard.string!)
let attributedString = self.attributedText.mutableCopy() as! NSMutableAttributedString
attributedString.replaceCharactersInRange(self.selectedRange, withAttributedString: text)
self.attributedText = attributedString
}
}
}
另外,我的textView的IBOutlet在另一个文件中,并且是我创建的这个自定义类型:
@IBOutlet var textView: CustomUITextView!
我创建了UITextView的子类并将其分配给我的textview。然后我覆盖粘贴功能以允许图像,因为我读到UITextField默认情况下不支持图像粘贴。这目前适用于文本但不适用于图像--->如果我做一个长按手势来显示菜单,"粘贴"如果PasteBoard中有图像,则按钮永远不会显示;它只显示是否有文字。
最终,我想在我的textview中粘贴来自URLS的PNG,JPEGS和图像。有人请帮忙!!