一个简单的用于文件拖放的视图类。支持 Swift、SwiftUI 和 Objective-C。
我多次需要类似的东西。所以这是一个模块,也许可以让我未来的生活更轻松。
将 https://github.com/dagronf/DSFDropFilesView
添加到您的项目中。
使用 Interface Builder 添加一个新的 NSView
实例,然后将类类型更改为 DSFDropFilesView
let dropView = DSFDropFilesView(frame: .zero)
见下文。
将 https://github.com/dagronf/DSFDropFilesView
添加到您的项目中。
请注意,如果您需要在支持 macOS 10.14 之前的 Objective-C 项目中使用 DSFDropFilesView
,您还需要确保在项目设置中将 Always Embed Swift Standard Libraries
设置为 Yes
。 在 macOS 10.14 之前,Swift 标准库不作为 macOS 安装的一部分分发,您需要在您的应用程序中提供您自己的标准库。
要接收来自控件的回调,请将 dropDelegate
设置为您的视图控制器。
@objc optional func dropFilesViewWantsSelectFiles(_ sender: DSFDropFilesView)
一个可选的方法,当用户点击控件上的“选择文件...”按钮时被调用。
func dropFilesView(_ sender: DSFDropFilesView, validateFiles: [URL]) -> NSDragOperation
当拖动进入视图时调用。返回拖动操作(或一个空数组)以指示拖动如何继续。 使用此函数来过滤掉“错误”类型的文件。(例如,如果您只想接收 PDF)。
func dropFilesView(_ sender: DSFDropFilesView, didDropFiles files: [URL]) -> Bool
当用户实际放下文件时调用,并携带文件列表。
这些属性都可以通过 Interface Builder 或通过编程方式进行配置。
allowsMultipleDrop
:允许拖放多个文件/文件夹selectFilesButtonLabel
:嵌入一个可点击的按钮,用于辅助功能,并带有指定的标签。 如果为空,则不显示按钮(默认)selectFilesButtonIsLink
:如果显示选择文件按钮,则将该按钮显示为超链接(蓝色带下划线的文本)而不是按钮。showIcon
:是否显示图标icon
:要显示的图标。 提供了一个默认图标label
:标签的文本。 如果为空,则隐藏标签。lineWidth
:虚线边框的线宽cornerWidth
:角部的半径有一个基本的 SwiftUI View,它嵌入了 DSFDropFilesView
控件。
DSFDropFilesView.SwiftUI(
isEnabled: true,
allowsMultipleDrop: true,
iconLabel: "Drop files here",
selectFilesLabel: "Select Files…",
selectFilesButtonIsLink: true,
validateFiles: { urls in
// Check the urls, and return the appropriate drop mode
return .copy
},
dropFiles: { urls in
Swift.print("\(urls)")
return true
},
selectFiles: {
Swift.print("User clicked select files")
}
)
MIT License
Copyright (c) 2024 Darren Ford
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.