关于使用NSOpenPanel的详细说明

jim*_*b99 10 swift

我希望能够在Swift中打开图像.这是我的第一个Swift项目.

@IBAction func SelectFileToOpen(sender: NSMenuItem) {
    var openPanel = NSOpenPanel();
    openPanel.allowsMultipleSelection = false;
    openPanel.canChooseDirectories = false;
    openPanel.canCreateDirectories = false;
    openPanel.canChooseFiles = true;
    let i = openPanel.runModal();
    if(i == NSOKButton){
        print(openPanel.URL);
        var lettersPic = NSImage(contentsOfURL: openPanel.URL!);
        imageView.image = lettersPic;

    }
}
Run Code Online (Sandbox Code Playgroud)

NSLog使用打开面板时的输出

Optional(file:///Users/ethansanford/Desktop/BigWriting.png)
fatal error: unexpectedly found nil while unwrapping an Optional value
Run Code Online (Sandbox Code Playgroud)

如何允许用户打开感兴趣的png文件.当我在代码中指定相同的文件时一切正常.我的一个示例,指示在不使用打开文件面板并充当用户的情况下在代码中打开哪个文件:

let pictureURl = NSURL(fileURLWithPath: "///Users/ethansanford/Desktop/BigWriting.png");
var lettersPic = NSImage(contentsOfURL: pictureURl!);
imageView.image = lettersPic; 
Run Code Online (Sandbox Code Playgroud)

我的网址格式有问题吗?任何帮助,将不胜感激.

Leo*_*bus 17

将新文件添加到项目中(swift源文件)并在此处添加此扩展名

Xcode 9•Swift 4

extension NSOpenPanel {
    var selectUrl: URL? {
        title = "Select Image"
        allowsMultipleSelection = false
        canChooseDirectories = false
        canChooseFiles = true
        canCreateDirectories = false
        allowedFileTypes = ["jpg","png","pdf","pct", "bmp", "tiff"]  // to allow only images, just comment out this line to allow any file type to be selected 
        return runModal() == .OK ? urls.first : nil
    }
    var selectUrls: [URL]? {
        title = "Select Images"
        allowsMultipleSelection = true
        canChooseDirectories = false
        canChooseFiles = true
        canCreateDirectories = false
        allowedFileTypes = ["jpg","png","pdf","pct", "bmp", "tiff"]  // to allow only images, just comment out this line to allow any file type to be selected
        return runModal() == .OK ? urls : nil
    }
}
Run Code Online (Sandbox Code Playgroud)

在View Controller中:

class ViewController: NSViewController {
    @IBOutlet weak var imageView: NSImageView!
    @IBAction func saveDocument(_ sender: NSMenuItem) {
        print("SAVE")
    }
    @IBAction func newDocument(_ sender: NSMenuItem) {
        print("NEW")
    }
    // connect your view controller to the first responder window adding the openDocument method
    @IBAction func openDocument(_ sender: NSMenuItem) {
        print("openDocument ViewController")
        if let url = NSOpenPanel().selectUrl {
            imageView.image = NSImage(contentsOf: url)
            print("file selected:", url.path)
        } else {
            print("file selection was canceled")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


jwl*_*ton 5

嗯......我没有发现你的代码有任何问题,所以我测试运行了这个代码(在我的桌面上选择一个 PNG 文件):

let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = false
openPanel.canCreateDirectories = false
openPanel.canChooseFiles = true
let i = openPanel.runModal()
if(i == NSModalResponseOK){
    print(openPanel.URL)
    let lettersPic = NSImage(contentsOfURL: openPanel.URL!)
    print(lettersPic)      
}
Run Code Online (Sandbox Code Playgroud)

我得到的是:

可选(file:///Users/jwlaughton/Desktop/flame%2012-32.png)
可选( "NSBitmapImageRep 0x6000000a4140 Size={1440, 900} ColorSpace=(尚未加载) BPS=8 BPP=(尚未加载)像素=1440x900 Alpha=NO Planar=NO Format=(尚未加载) CurrentBacking=nil (故障) CGImageSource=0x608000160cc0" )>)

这对我来说似乎没问题。

也许问题是你需要说:

imageView.image = lettersPic!; 
Run Code Online (Sandbox Code Playgroud)

编辑:

因此,为了进一步测试,我将测试代码稍微扩展为:

if(i == NSOKButton){
    print(openPanel.URL);

    var lettersPic = NSImage(contentsOfURL: openPanel.URL!);
    print(lettersPic);
    let view:NSImageView = NSImageView();
    view.image = lettersPic

    print(view)
}
Run Code Online (Sandbox Code Playgroud)

一切仍然正常。抱歉,我无法重现您的问题。