NSOpenPanel - Everything deprecated?

前端 未结 3 1728
花落未央
花落未央 2021-02-07 23:43

I\'ve been trying to get a window to show up asking the person to choose a file, and I eventually did. The problem is, Xcode complains that the method I\'m using is deprecated.

3条回答
  •  不知归路
    2021-02-07 23:55

    Seeing how I found this question useful six years later, and since there are no swift answers, here's a swift solution.

    You'll find two samples, one as a stand alone window and the other as a sheet.

    Swift 3.0

    func selectIcon() {
        // create panel
        let panel = NSOpenPanel()
    
        // configure as desired
        panel.canChooseFiles = true
        panel.canChooseDirectories = false
        panel.allowsMultipleSelection = false
        panel.allowedFileTypes = ["png"]
    
        // *** ONLY USE ONE OF THE FOLLOWING OPTIONS, NOT BOTH ***
    
        // ********************** OPTION 1 ***********************
        // use this if you want a selection window to display that is
        // displayed as a separate stand alone window
        panel.begin { [weak self] (result) in
            guard result == NSFileHandlingPanelOKButton, panel.urls.isEmpty == false, let url = panel.urls.first else {
                return
            }
    
            let image = NSImage.init(contentsOf: url)
            DispatchQueue.main.async {
                self?.iconImageView.image = image
            }
        }
    
        // ********************** OPTION 2 ***********************        
        // use this if you want a sheet style view that displays sliding
        // down from your apps window
        panel.beginSheetModal(for: self.view.window!) { [weak self] (result) in
            guard result == NSFileHandlingPanelOKButton, panel.urls.isEmpty == false, let url = panel.urls.first else {
                return
            }
    
            let image = NSImage.init(contentsOf: url)
            DispatchQueue.main.async {
                self?.iconImageView.image = image
            }
        }
    }
    

提交回复
热议问题