简体   繁体   中英

How to implement printer picker using SwiftUI?

I have Used UIPrinterPickerController class to implement printer picker. Now I want to implement printer picker using SwiftUI . I tried my best but did not find any solution. I will really appreciate your help.

Yes, it is not so trivial, so here is possible approach. Tested & works with Xcode 11.4 / iOS 13.4

Note: make sure you activate Printing in project Signing & Capabilities settings.

I don't have AirPrint printers around, so ... just searching

在此处输入图像描述

Demo code:

struct DemoPrinterPicker: View {
    @State private var showPicker = false

    var body: some View {
        Button("Select Printer") {
            self.showPicker.toggle()
        }
        .background(PrinterPickerController(showPrinterPicker: $showPicker))
    }
}

SwiftUI representable (just shows printers picker, what to do with selected printer is your responsibility)

struct PrinterPickerController: UIViewControllerRepresentable {
    @Binding var showPrinterPicker: Bool

    fileprivate let controller = UIViewController()

    func makeUIViewController(context: Context) -> UIViewController {
        controller
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        if showPrinterPicker && context.coordinator.activePicker == nil {
            let picker = UIPrinterPickerController(initiallySelectedPrinter: nil)
            context.coordinator.activePicker = picker

            picker.delegate = context.coordinator
            picker.present(animated: true) { (picker, flag, error) in
                if let printer =  picker.selectedPrinter {
                    // << do anything needed with printer
                }

                context.coordinator.activePicker = nil
                self.showPrinterPicker = false
            }
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, UIPrinterPickerControllerDelegate {
        let owner: PrinterPickerController
        var activePicker: UIPrinterPickerController?

        init(_ owner: PrinterPickerController) {
            self.owner = owner
        }

        func printerPickerControllerParentViewController(_ printerPickerController: UIPrinterPickerController) -> UIViewController? {
            self.owner.controller
        }
    }
    
    typealias UIViewControllerType = UIViewController
}

backup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM