2017-08-16 51 views
0

我遇到了有关我的NSTextView子类的问题。我的视图包含带有自定义属性的属性字符串,因此我必须实施以下粘贴板方法,以确保将自定义属性复制到粘贴板上。NSTextView将文本拖动到自定义属性

writeSelection(to:type:) 
readSelection(from:type:) 

在readSelection,我手动读取粘贴板上的字符串,并将其写入到NSTextView的在rangeForUserTextChange textStorage。

override func readSelection(from pboard: NSPasteboard, type: String) -> Bool { 


    // Manually reads the text on the pasteboard, and write it to textStorage 

    if type == astroBoardAttributedString { 

     if let string = pboard.string(forType: astroBoardAttributedString) { 

      let attrString = NSAttributedString(string: string) 

      self.textStorage?.replaceCharacters(in: self.rangeForUserTextChange, with: attrString) 


      return true 

     } 


    } 

    return super.readSelection(from: pboard, type: type) 

} 

现在的问题是,当我选择并拖动文本上来就说从5号线到线下1,文本是根据1号线插入正确,但系统会尝试删除从那里使用的5号线文是,它现在包含4行,因为一个额外的行已添加以下线路1

enter image description here

/* 
line 1 <-- Drop after this line 
line 2 
line 3 
line 4 
line 5 <-- Drag from this line 

The expected outcome is 

line 1 
line 5 
line 2 
line 3 
line 4 

The actual resulting outcome is 

line 1 
line 5 
line 2 
line 3 
line 5 

What happens is 

line 1 
line 5 <-- Line inserted here (correct) 
line 2 
line 3 
line 4 <-- This line is removed instead :(
line 5 <-- This is the line that should be removed. 
*/ 

正如你所看到的,该系统消除线路长度已经改变了。当拖放方法删除从textview拖动的textStorage中的文本时,我无法找到任何拦截代理的方法。

回答

0

联系Apple寻求支持后,我得到了答案,这里是引用。

的代码片段您提供的节目,当你从剪贴板读取和改变文本存储,你不通过调用shouldChangeText(...)和didChangeText(),这将导致不一致notifiy其他组件文字之间的存储和渲染。您应该可以通过包装代码来解决问题,如下所示:

self.shouldChangeText(in:self.rangeForUserTextChange, replacementString: string) 
self.textStorage?.replaceCharacters(in: self.rangeForUserTextChange, with: string) 
self.didChangeText()