2017-08-16 56 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()