NSOpenPanel使用详解
Detailed instruction on use of NSOpenPanel
我希望能够在 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;
}
}
我的 NSLog
使用打开面板时的输出
Optional(file:///Users/ethansanford/Desktop/BigWriting.png)
fatal error: unexpectedly found nil while unwrapping an Optional value
如何让用户打开感兴趣的 png 文件。
当我在代码中指定相同的文件时,一切正常。我的一个示例,在不使用打开文件面板并作为用户的情况下指示在代码中打开哪个文件:
let pictureURl = NSURL(fileURLWithPath: "///Users/ethansanford/Desktop/BigWriting.png");
var lettersPic = NSImage(contentsOfURL: pictureURl!);
imageView.image = lettersPic;
我的URL格式有问题吗?任何帮助,将不胜感激。
嗯...我没有发现您的代码有任何问题,所以我测试了运行这段代码(在我的桌面上选择一个 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)
}
我得到的是:
Optional(file:///Users/jwlaughton/Desktop/flame%2012-32.png)
Optional(
"NSBitmapImageRep 0x6000000a4140 Size={1440, 900} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=1440x900 Alpha=NO
Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting)
CGImageSource=0x608000160cc0" )>)
我觉得还可以。
也许问题是你需要说:
imageView.image = lettersPic!;
编辑:
所以为了进一步测试,我将测试代码稍微扩展为:
if(i == NSOKButton){
print(openPanel.URL);
var lettersPic = NSImage(contentsOfURL: openPanel.URL!);
print(lettersPic);
let view:NSImageView = NSImageView();
view.image = lettersPic
print(view)
}
一切正常。抱歉,我无法重现您的问题。
向您的项目添加一个新文件(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
}
}
在您的视图控制器中:
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")
}
}
}
这是最终为我工作的代码。我不得不禁用故事板。我必须制作一个名为 Main 的 class。这不要与一个名为 main.swift 的特殊 class 混淆,它取代了 appdelegate.swift.And 我也必须导入 Cocoa。然后我必须指定从 nsobject 继承的 main。这样我就可以首先在界面构建器之间建立连接,并将 ibactions 和 outlets 放入我的 Main.swift 文件中。
//
// Main.swift
// Open
//
// Created by ethan sanford on 2015-01-18.
// Copyright (c) 2015 ethan D sanford. All rights reserved.
//
import Foundation
import Cocoa
class Main: NSObject{
@IBOutlet var imageWell: NSImageCell!
var myURL = NSURL(fileURLWithPath: "")
@IBAction func main(sender: AnyObject) {
imageWell.image = NSImage(byReferencingURL: myURL!)
}
@IBAction func open(sender: AnyObject) {
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);
myURL = openPanel.URL;
}
}
}
它的工作方式有点奇怪,您必须选择您的文件并单击打开。然后点击 @IBAction func main(sender: AnyObject) {
连接的按钮
我希望能够在 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;
}
}
我的 NSLog
使用打开面板时的输出
Optional(file:///Users/ethansanford/Desktop/BigWriting.png)
fatal error: unexpectedly found nil while unwrapping an Optional value
如何让用户打开感兴趣的 png 文件。 当我在代码中指定相同的文件时,一切正常。我的一个示例,在不使用打开文件面板并作为用户的情况下指示在代码中打开哪个文件:
let pictureURl = NSURL(fileURLWithPath: "///Users/ethansanford/Desktop/BigWriting.png");
var lettersPic = NSImage(contentsOfURL: pictureURl!);
imageView.image = lettersPic;
我的URL格式有问题吗?任何帮助,将不胜感激。
嗯...我没有发现您的代码有任何问题,所以我测试了运行这段代码(在我的桌面上选择一个 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)
}
我得到的是:
Optional(file:///Users/jwlaughton/Desktop/flame%2012-32.png)
Optional( "NSBitmapImageRep 0x6000000a4140 Size={1440, 900} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=1440x900 Alpha=NO Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x608000160cc0" )>)
我觉得还可以。
也许问题是你需要说:
imageView.image = lettersPic!;
编辑:
所以为了进一步测试,我将测试代码稍微扩展为:
if(i == NSOKButton){
print(openPanel.URL);
var lettersPic = NSImage(contentsOfURL: openPanel.URL!);
print(lettersPic);
let view:NSImageView = NSImageView();
view.image = lettersPic
print(view)
}
一切正常。抱歉,我无法重现您的问题。
向您的项目添加一个新文件(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
}
}
在您的视图控制器中:
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")
}
}
}
这是最终为我工作的代码。我不得不禁用故事板。我必须制作一个名为 Main 的 class。这不要与一个名为 main.swift 的特殊 class 混淆,它取代了 appdelegate.swift.And 我也必须导入 Cocoa。然后我必须指定从 nsobject 继承的 main。这样我就可以首先在界面构建器之间建立连接,并将 ibactions 和 outlets 放入我的 Main.swift 文件中。
//
// Main.swift
// Open
//
// Created by ethan sanford on 2015-01-18.
// Copyright (c) 2015 ethan D sanford. All rights reserved.
//
import Foundation
import Cocoa
class Main: NSObject{
@IBOutlet var imageWell: NSImageCell!
var myURL = NSURL(fileURLWithPath: "")
@IBAction func main(sender: AnyObject) {
imageWell.image = NSImage(byReferencingURL: myURL!)
}
@IBAction func open(sender: AnyObject) {
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);
myURL = openPanel.URL;
}
}
}
它的工作方式有点奇怪,您必须选择您的文件并单击打开。然后点击 @IBAction func main(sender: AnyObject) {