Created
November 22, 2023 12:31
-
-
Save sharaththegeek/9b8900a6e6908f1b6b84054754592fd1 to your computer and use it in GitHub Desktop.
ContactPicker in SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import ContactsUI | |
public struct ContactPicker: UIViewControllerRepresentable { | |
@Binding var isPresented: Bool | |
var onSelect: (CNContact) -> Void | |
public func makeUIViewController(context: Context) -> some UIViewController { | |
let navController = UINavigationController() | |
let pickerVC = CNContactPickerViewController() | |
pickerVC.delegate = context.coordinator | |
navController.pushViewController(pickerVC, animated: false) | |
navController.isNavigationBarHidden = true | |
return navController | |
} | |
public func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { | |
} | |
public func makeCoordinator() -> Coordinator { | |
return Coordinator(parent: self) | |
} | |
public class Coordinator: NSObject, CNContactPickerDelegate { | |
var parent: ContactPicker | |
init(parent: ContactPicker) { | |
self.parent = parent | |
} | |
public func contactPickerDidCancel(_ picker: CNContactPickerViewController) { | |
} | |
public func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) { | |
parent.onSelect(contact) | |
} | |
} | |
} | |
struct ContactPickerViewModifier: ViewModifier { | |
@Binding var isPresented: Bool | |
var onDismiss: (() -> Void)? | |
var onSelect: ((CNContact) -> Void) | |
func body(content: Content) -> some View { | |
content | |
.sheet(isPresented: $isPresented, onDismiss: onDismiss) { | |
ContactPicker(isPresented: $isPresented, onSelect: onSelect) | |
} | |
} | |
} | |
public extension View { | |
func contactPicker(isPresented: Binding<Bool>, onDismiss: (() -> Void)?, onSelect: @escaping ((CNContact) -> Void)) -> some View { | |
modifier(ContactPickerViewModifier(isPresented: isPresented, onDismiss: onDismiss, onSelect: onSelect)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment