Mac app开发跟ios开发有点区别,网上教程比较少
这个例子是,点击按钮以后,打开选择文件夹的窗口,可以多选文件夹,另一个按钮可以多选文件.然后打印出目录 运行效果 NSOpenPanel讲解
首先把2个按钮连线到swift文件中,2个按钮代码如下:
NSOpenPanel 创建对象以后通过 设置属性canChooseDirectories和canChooseFiles实现打开文件或者文件夹
通过block beginSheetModal实现打开文件窗口.
var pathUrls = [URL]()//保存选择所有文件的路径数组
//MARK: - 选择文件
@IBAction func btnOpenFileClick(_ sender: Any) {
let openPanel = NSOpenPanel()
openPanel.prompt = "选择"
openPanel.canChooseDirectories = false //不允许选择目录
openPanel.canChooseFiles = true //选择文件
openPanel.allowsMultipleSelection = true//允许多选
openPanel.beginSheetModal(for: view.window!) {[unowned self] result in
if result != .OK { //result是点击的结果,如果点击确定result == .OK
print("点击取消")
return
}
//遍历多选的所有路径
for url in openPanel.urls{
print("路径是=",url.path)
}
pathUrls = openPanel.urls
}
}
//MARK: - 选择目录
@IBAction func btnOpenDirClick(_ sender: Any) {
let openPanel = NSOpenPanel()
openPanel.prompt = "选择"
openPanel.canChooseDirectories = true //
openPanel.allowsMultipleSelection = true
openPanel.canChooseFiles = false
openPanel.beginSheetModal(for: view.window!) { [unowned self] result in
if result != .OK {
print("点击取消")
return
}
//遍历多选的所有路径
for url in openPanel.urls{
print("路径是=",url.path)
}
pathUrls = openPanel.urls
}
}
//MARK: - 用finder打开文件所在位置
@IBAction func btnOpenPathClick(_ sender: Any) {
print("pathUrls=",pathUrls)
NSWorkspace.shared.activateFileViewerSelecting(pathUrls)
}
swift代码 demo下载
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)