我希望能够在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)
我的网址格式有问题吗?任何帮助,将不胜感激.
swift ×1