图像拖放到NSTextView时如何找到它的光标位置?

时间:2019-11-28 12:11:44

标签: swift cocoa appkit nstextview

我想在光标所在的位置的NSTextview中插入图像,但是将图像插入NSTexview的选定范围而不是放下图像时的确切位置。

例如,我将图像放在字符“ 4”之后:
enter image description here

但是图像是在9之后插入的,这是textview所选范围的位置: enter image description here 如何在放置位置插入图像?

我的代码:

import Cocoa

let screenSize = NSScreen.main!.frame.size

class ViewController: NSViewController {

  override func viewDidLoad() {
      let imgImage1 = NSTextView(frame: NSRect(x: 10, y: 200, width: 1000, height: 300))
      imgImage1.string = "1\n2\n3\n4\n5\n6\n7\n8\n9"
      self.view.addSubview(imgImage1)
  }

}

extension NSTextView{



override open func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
    guard let pasteboard = sender.draggingPasteboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray,
                 let path = pasteboard[0] as? String
           else { return false }
           let theImage = NSImage(byReferencingFile: path)!
           theImage.size = NSSize(width: 50, height: 50)
           guard let store = self.textStorage else { abort() }
           let cell = NSTextAttachmentCell(imageCell: theImage)
           let txtAtt = NSTextAttachment(data: theImage.tiffRepresentation, ofType: kUTTypeJPEG as String)
           txtAtt.attachmentCell = cell
           let str = NSAttributedString(attachment: txtAtt)
           let range = self.selectedRange()
           store.replaceCharacters(in: range, with: str)

           return true
}
}

0 个答案:

没有答案