Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,29 @@ CountryCodePicker.commonCountryCodes = ["US", "GB", "FR"]
textField.withDefaultPickerUIOptions.backgroundColor = .systemBackground
```

### SwiftUI

Use `PhoneNumberTextFieldRepresentable` to bind a text field to SwiftUI state. Configure the
underlying `PhoneNumberTextField` in the trailing closure:

```swift
import SwiftUI
import PhoneNumberKitUI

struct ContentView: View {
@State private var phoneNumber = ""

var body: some View {
PhoneNumberTextFieldRepresentable(text: $phoneNumber) { textField in
textField.withFlag = true
textField.withPrefix = true
textField.withExamplePlaceholder = true
textField.withDefaultPickerUI = true
}
}
}
```

Override the default region by subclassing:

```swift
Expand Down
55 changes: 55 additions & 0 deletions Sources/PhoneNumberKitUI/PhoneNumberTextFieldRepresentable.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import SwiftUI

/// A SwiftUI wrapper around ``PhoneNumberTextField``.
public struct PhoneNumberTextFieldRepresentable: UIViewRepresentable {
@Binding private var text: String
private let configure: (PhoneNumberTextField) -> Void

/// Creates a phone number text field bound to a string.
///
/// - Parameters:
/// - text: The text displayed and edited by the text field.
/// - configure: A closure for configuring the underlying UIKit text field.
public init(
text: Binding<String>,
configure: @escaping (PhoneNumberTextField) -> Void = { _ in }
) {
_text = text
self.configure = configure
}

public func makeUIView(context: Context) -> PhoneNumberTextField {
let textField = PhoneNumberTextField()
configure(textField)
textField.addTarget(
context.coordinator,
action: #selector(Coordinator.textDidChange(_:)),
for: .editingChanged
)
return textField
}

public func updateUIView(_ textField: PhoneNumberTextField, context: Context) {
context.coordinator.parent = self

if textField.text != text {
textField.text = text
}
}

public func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}

public final class Coordinator: NSObject {
fileprivate var parent: PhoneNumberTextFieldRepresentable

fileprivate init(parent: PhoneNumberTextFieldRepresentable) {
self.parent = parent
}

@objc fileprivate func textDidChange(_ textField: PhoneNumberTextField) {
parent.text = textField.text ?? ""
}
}
}