2014-10-31 31 views
2

我試圖通過Xcode和Swift在OSX中顯示一個打開的文件對話框。 然後我想把文件名放在TextField中。如何將NSOpenPanel.URL轉換爲字符串?

我開始與

@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」的問題是不是字符串和所有試圖施放失敗。

我確實讓它工作,所以我想我會在這裏發佈答案。

+1

var thefile:NSString = f.URLs [0] .absoluteString! – 2014-11-03 09:24:10

回答

0

下面是代碼結束了工作 注意我創建了一個名爲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! 
}