我试图通过 Xcode 和 Swift 在 OSX 中显示一个打开的文件对话框。 然后我想将文件名放在 TextField 中。
我从
开始@IBOutlet weak var lblFileName: NSTextField!
@IBAction func FileOpen(sender: AnyObject) {
var f:NSOpenPanel = NSOpenPanel()
f.title = "open that file"
f.allowsMultipleSelection = false
f.canChooseDirectories = false
f.runModal()
var thefile = f.URLs[0].absoluteString
println(thefile)
//failed: lblFileName.stringValue = thefile
lblFileName.stringValue = "I want this to be the filename!"
}
println(thefile) 有效,所以这只是转换 URL 的问题 变量“thefile”不是字符串,所有尝试转换它的尝试都失败了。
我确实让它工作了,所以我想我也应该在这里发布答案。
最佳答案
这是最终运行的代码 注意我创建了一个名为 mystring 的字符串并且必须使用 ?和!使事情正常进行。 如果有更简单/更好的方法,请在评论中添加!
@IBOutlet weak var lblFileName: NSTextField!
@IBAction func FileOpen(sender: AnyObject) {
var f:NSOpenPanel = NSOpenPanel()
f.title = "open that file"
f.allowsMultipleSelection = false
f.canChooseDirectories = false
f.runModal()
var thefile = f.URLs[0].absoluteString
println(thefile)
var mystring:String? = thefile
lblFileName.stringValue = mystring!
}
关于macos - 如何将 NSOpenPanel.URL 转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26667023/