2014-10-28 20 views
10

Ich habe diese Objective-C-Code:NSOpenPanel in Swift. Wie Öffnen?

- (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]; 
      } 

     } 
    }]; 

Jetzt möchte ich dies das Gleiche in geschickter schreiben. Hier ist, was ich bis jetzt getan habe:

@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) 
} 

und hier bin ich fest. Danke für Hilfe.

Antwort

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 
     } 
    } 
} 

Ich nehme an, Sie stecken auf dem Completion-Handler Teil fest? In jedem Fall sollte die Handhabung der URL aus dem offenen Panel von dort aus in Ordnung sein, aber kommentiere, wenn ich mehr hinzufügen möchte. :)

0

Swift 4 Version:

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

Für Swift 4 die Überprüfung der Antwort sollte

if response = .OK { 
    ... 
} 
sein