2014-10-28 80 views
10

我有這樣的Objective-C代碼:Swift中的NSOpenPanel。如何打開?

- (IBAction)selectFileButtonAction:(id)sender { 

    //create open panel... 
    NSOpenPanel* openPanel = [NSOpenPanel openPanel]; 
    // NSLog(@"Open Panel"); 
    //set restrictions/allowances... 
    [openPanel setAllowsMultipleSelection: NO]; 
    [openPanel setCanChooseDirectories:NO]; 
    [openPanel setCanCreateDirectories:NO]; 
    [openPanel setCanChooseFiles:YES]; 
    //only allow images... 
    [openPanel setAllowedFileTypes:[NSImage imageFileTypes]]; 
    //open panel as sheet on main window... 
    [openPanel beginWithCompletionHandler:^(NSInteger result) { 
     if (result == NSFileHandlingPanelOKButton) { 

      //get url (should only be one due to restrictions)... 
      for(NSURL* URL in [openPanel URLs]) { 
       // self.roundClockView1.URL = URL ; 
       _thePath = URL; 
       currentSelectedFileName = [[URL path] lastPathComponent]; 
       // [_roundClockView1 setNeedsDisplay:1]; 
       [self openEditor]; 
      } 

     } 
    }]; 

現在我想寫這SWIFT同樣的事情。這是我迄今爲止所做的:

@IBAction func selectAnImageFromFile(sender: AnyObject) { 
    var openPanel = NSOpenPanel() 
    openPanel.allowsMultipleSelection = false 
    openPanel.canChooseDirectories = false 
    openPanel.canCreateDirectories = false 
    openPanel.canChooseFiles = true 
    openPanel.beginWithCompletionHandler(handler: (Int) -> Void) 
} 

這裏我卡住了。 感謝您的幫助。

回答

32
@IBAction func selectAnImageFromFile(sender: AnyObject) { 
    let openPanel = NSOpenPanel() 
    openPanel.allowsMultipleSelection = false 
    openPanel.canChooseDirectories = false 
    openPanel.canCreateDirectories = false 
    openPanel.canChooseFiles = true 
    openPanel.beginWithCompletionHandler { (result) -> Void in 
     if result == NSFileHandlingPanelOKButton { 
      //Do what you will 
      //If there's only one URL, surely 'openPanel.URL' 
      //but otherwise a for loop works 
     } 
    } 
} 

我猜你被卡在完成處理程序部分?無論如何,從打開的面板處理URL應該沒問題,但如果您想要添加更多內容,請發表評論。 :)

0

斯威夫特4版本:

let openPanel = NSOpenPanel() 
     openPanel.canChooseFiles = false 
     openPanel.allowsMultipleSelection = false 
     openPanel.canChooseDirectories = false 
     openPanel.canCreateDirectories = false 
     openPanel.title = "Select a folder" 

     openPanel.beginSheetModal(for:self.view.window!) { (response) in 
      if response.rawValue == NSFileHandlingPanelOKButton { 
       let selectedPath = openPanel.url!.path 
       // do whatever you what with the file path 
      } 
      openPanel.close() 
     } 
1

對於斯威夫特4響應的檢查應

if response = .OK { 
    ... 
}