mobven / CountryPicker

Country Picker with unicode flags and country codes.
MIT License
66 stars 19 forks source link

Example of UIViewControllerRepresentable #4

Closed hcancelik closed 2 years ago

hcancelik commented 2 years ago

Here is an example of UIViewControllerRepresentable that works with SwiftUI.

Please feel free to add this to docs.

//
//  CountryPicker.swift
//

import SwiftUI
import CountryPicker

struct CountryPicker: UIViewControllerRepresentable {
    @Binding var country: Country?

    typealias UIViewControllerType = CountryPickerViewController

    let countryPicker = CountryPickerViewController()

    func makeUIViewController(context: Context) -> CountryPickerViewController {
        countryPicker.selectedCountry = Locale.current.regionCode ?? "US"
        countryPicker.delegate = context.coordinator

        return countryPicker
    }

    func updateUIViewController(_ uiViewController: CountryPickerViewController, context: Context) {
        //
    }

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

    class Coordinator: NSObject, CountryPickerDelegate {
        var parent: CountryPicker

        init(_ parent: CountryPicker) {
            self.parent = parent
        }

        func countryPicker(didSelect country: Country) {
            parent.country = country
        }
    }
}

Example Usage:

//
//  ContentView.swift
//

import SwiftUI
import CountryPicker

struct ContentView: View {
    @State private var country: Country?
    @State private var showCountryPicker = false

    var body: some View {
        VStack {
            Button {
                showCountryPicker = true
            } label: {
                Text("Select Country")
            }.sheet(isPresented: $showCountryPicker) {
                CountryPicker(country: $country)
            }
        }
    }
}
Rashidium commented 2 years ago

Thanks for feedback @hcancelik . We'll include SwiftUI implementation on the readme.

HussainSatham commented 2 years ago

With swiftui, how you will get the selected country details back? @hcancelik @Rashidium

hcancelik commented 2 years ago

With swiftui, how you will get the selected country details back? @hcancelik @Rashidium

From the example above, it will be set to country property.

Button {
    showCountryPicker = true
} label: {
    Text("Select Country \(country?.localizedName ?? "Not Selected")")
}.sheet(isPresented: $showCountryPicker) {
    CountryPicker(country: $country)
}