macOS-如何让NSSavePanel在文件名中添加文件扩展名? [英] macOS - How to have NSSavePanel to add a file extension in the file name?

查看:149
本文介绍了macOS-如何让NSSavePanel在文件名中添加文件扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码为用户提供选择,以指定用于在磁盘上保存纯文本文件的名称和位置.一切似乎正常,但保存的文件没有任何扩展名.实际上,我没有在代码的任何部分中指定扩展名,我在阅读NSSavePanel文档时没有注意到解释此选项的部分.

I'm using this code to give the user the choice to specify a name and a location where to save a plain text file on disk. All seems to work but the saved file hasn't any extension. Actually I have not specify an extension in any part of my code, I read NSSavePanel documentation without notice the part where explained this option.

这是我正在使用的代码:

Here is the code I'm using:

    let textToExport = mainTextField.textStorage?.string

    if textToExport != "" {
        let mySave = NSSavePanel()

        mySave.begin { (result) -> Void in

            if result == NSFileHandlingPanelOKButton {
                let filename = mySave.url

                do {
                    try textToExport?.write(to: filename!, atomically: true, encoding: String.Encoding.utf8)
                } catch {
                    // failed to write file (bad permissions, bad filename etc.)
                }

            } else {
                NSBeep()
            }
        }
    }

推荐答案

添加行

mySave.allowedFileTypes = ["txt"]

在展示面板之前.

文档:

此属性的值指定用户可以保存的文件类型 文件为.文件类型可以是通用文件扩展名,也可以是UTI.这 此属性的默认值为nil,表示任何文件 类型可以使用. (请注意,如果数组不是nil并且该数组 不包含任何项目,则会引发异常.)

The value of this property specifies the file types the user can save the file as. A file type can be a common file extension, or a UTI. The default value of this property is nil, which indicates that any file type can be used. (Note that if the array is not nil and the array contains no items, an exception is raised.)

如果用户未给出扩展名,则 allowedFileTypes数组将用作保存的扩展名 控制板.如果用户指定的类型不在数组中,并且 allowOtherFileTypes为true,它们将与另一个 提示保存时显示对话框.

If no extension is given by the user, the first item in the allowedFileTypes array will be used as the extension for the save panel. If the user specifies a type not in the array, and allowsOtherFileTypes is true, they will be presented with another dialog when prompted to save.

这篇关于macOS-如何让NSSavePanel在文件名中添加文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆