【问题标题】:Is there a way to make the default NSDragOperation Move and still allow Copy?有没有办法让默认的 NSDragOperation 移动并仍然允许复制?
【发布时间】:2016-10-28 01:33:58
【问题描述】:

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

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

【问题讨论】:

    标签: swift cocoa drag-and-drop


    【解决方案1】:

    您可以检查在返回 NSDragOperation 时是否按下了 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
    }
    

    【讨论】:

    • 这行得通。此外,我需要按照 Kevin Low 的建议将此代码添加到“draggingUpdated”
    • 此外,我必须将密钥检查添加到 performDragOperation(sender: NSDraggingInfo)。到达此方法时,拖动操作始终为 .None。 draggingSession(session: NSDraggingSession,endedAtPoint screenPoint: NSPoint, operation: NSDragOperation) 确实包含正确的操作。所以一切都通过检查 3 个地方的键来工作,但我认为我应该只需要检查 draggingUpdated,我想默认行为是覆盖这是某种方式。谢谢!
    【解决方案2】:

    您将保持 draggingSession:sourceOperationMaskForDraggingContext: 函数不变,因为它只在拖动开始时被调用,而大多数具有复制/移动功能的应用程序允许用户在拖动期间按下选项(更重要的是,当他们的光标在行/视图上)。

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

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

    【讨论】:

      【解决方案3】:

      我能够通过在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;
      }
      

      (它是 Objective-C,但我还是希望这一点很清楚。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-11
        • 1970-01-01
        • 2013-10-03
        • 2023-02-14
        • 1970-01-01
        • 1970-01-01
        • 2019-06-18
        • 1970-01-01
        相关资源
        最近更新 更多