Swift 是否有办法使默认NSDragOperation移动并仍允许复制?

Swift 是否有办法使默认NSDragOperation移动并仍允许复制?,swift,cocoa,drag-and-drop,Swift,Cocoa,Drag And Drop,在某些应用程序(例如GarageBand)中,最初的拖动操作是移动,如果在拖动时按Option键,则支持复制。 我试过几件事,但都没有成功。如果在操作掩码中指定.Copy,它将始终成为默认操作。这可能吗 func draggingSession(session: NSDraggingSession, sourceOperationMaskForDraggingContext context: NSDraggingContext) -> NSDragOperation { i

在某些应用程序(例如GarageBand)中,最初的拖动操作是移动,如果在拖动时按Option键,则支持复制。 我试过几件事,但都没有成功。如果在操作掩码中指定.Copy,它将始终成为默认操作。这可能吗

    func draggingSession(session: NSDraggingSession, sourceOperationMaskForDraggingContext context: NSDraggingContext) -> NSDragOperation {
    if context == NSDraggingContext.OutsideApplication
    {
        return .None
    }
    else
    {
        return [.Move,.Copy]
    }
}

返回NSDRAGO操作时,您可以检查是否按下了ALT(选项)键

例如:

if context == NSDraggingContext.OutsideApplication {
    return .None
} else {
    // get the current global event object 
    // and compare its modifier flags with ours
    if let event = NSApplication.sharedApplication().currentEvent
        where event.modifierFlags.contains(.AlternateKeyMask) {
            // ALT key is pressed
            return .Copy
    }
    // ALT key is not pressed
    return .Move
}

您可以保持
draggingSession:sourceOperationMaskForDraggingContext:
函数不变,因为它只在拖动开始时被调用,而大多数具有复制/移动功能的应用程序允许用户在拖动过程中按option(更重要的是,当光标位于行/视图上时)

如果您使用的是
NSDraggingDestination
,则可以在
draggingUpdated:
中检查此选项键


如果您使用的是
NSTableView
NSOutlineView
,那么您可以在他们的
validateDrop:
数据源方法中检查这一点。

我能够通过在
NSDraggingSource
中使用以下标志组合来实现此行为:

- (NSDragOperation) draggingSession:(NSDraggingSession *)session
  sourceOperationMaskForDraggingContext:(NSDraggingContext)context
{
  // This combination of flags gives the behaviour we want, somehow:
  //   - it uses move pointer by default (no plus)
  //   - plus appears when pressing Alt and drop is allowed
  //   - pointer stays unchanged when pressing Cmd and drop is allowed
  //   - pointer stays unchanged when pressing Ctrl and drop is not allowed
  //
  // If using NSDragOperationEvery, this is not the case as we then get
  // the plus pointer by default.
  return NSDragOperationCopy |
         NSDragOperationMove |
         NSDragOperationGeneric |
         NSDragOperationMove |
         NSDragOperationDelete;
}

(这是客观的,但我希望这一点是明确的。)

这起作用了。此外,我需要按照Kevin Low的建议将此代码添加到“DragginUpdated”中。此外,我还必须将密钥检查添加到performDragOperation(发送方:NSDragginInfo)。达到此方法时,拖动操作始终为。无。DragingSession(会话:NSDragingSession,EndedaPoint屏幕点:NSPoint,操作:NSDragOperation)包含正确的操作。因此,通过在3个位置检查密钥,一切都可以正常工作,但我的意见是,我应该只需要在DragginUpdated中进行检查,我想默认行为会覆盖这是某种方式。谢谢