1

NSTokenField将标记从一个字段拖放到另一个字段时的默认拖动操作是NSDragOperationCopy. 执行拖动时按住 Command 键会将操作更改为NSDragOperationMove

如何反转此默认行为,以便默认移动令牌,并且仅在按住 Option 键时复制?

我试图模仿 Mail 中撰写窗口的行为,在该窗口中,将电子邮件令牌从 To 字段拖到 Cc 字段会默认移动令牌,并在按住 Option 键时复制它。

我已经尝试子类NSTokenField化并覆盖draggingEntered:返回NSDragOperationMove,但这似乎不起作用。


更新:

默认情况下,我最终打开了dragOperationForDraggingInfo:type:方法NSTextView并在实现中返回NSDragOperationMove。我还检查选项键是否关闭,NSDragOperationCopy如果为真则返回。目前这似乎按预期工作,但我不确定方法调配是否是最好的方法。

4

1 回答 1

0

感谢Willeke的评论,我通过子类NSTokenField化和实现未记录的NSTextViewDelegate方法来实现这一点textView:dragOperationForDraggingInfo:type:

这是我在NSTokenField子类中使用的确切代码:

class TokenField: NSTokenField { 
   
    @objc func textView(_ textView: NSTextView, dragOperationForDraggingInfo dragInfo: NSDraggingInfo, type: NSPasteboard.PasteboardType) -> NSDragOperation {

      // if option is pressed, always return .copy
      if NSApp.currentEvent?.modifierFlags.intersection(.deviceIndependentFlagsMask) == .option {
        return .copy
      }

      // if the source and destination are the same, we want default NSTokenField behavior
      if let source = dragInfo.draggingSource as? NSTextView, textView == source {
        return .generic
      }

      // default to .move
      return .move
    }

}
于 2021-03-16T00:46:01.100 回答