27

私はこのObjective-Cコードを持っています:

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

そしてここで私は立ち往生しています。手伝ってくれてありがとう。

4

6 に答える 6

8

Swift 4 の場合、応答のチェックは

if response == .OK { 
  ... 
}
于 2018-01-26T12:36:49.760 に答える
5

スウィフト 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()
        }
于 2018-01-17T11:08:57.397 に答える
0

SwiftUI で

    struct FileView: View {
    var body: some View {
        Button("Press Me") {
            let openPanel = NSOpenPanel()
            openPanel.prompt = "Select File"
            openPanel.allowsMultipleSelection = false
                openPanel.canChooseDirectories = false
                openPanel.canCreateDirectories = false
                openPanel.canChooseFiles = true
                openPanel.begin { (result) -> Void in
                    if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
                        let selectedPath = openPanel.url!.path
                        print(selectedPath)

                    }
                }
           }
        }
     }
于 2020-07-02T14:11:33.447 に答える