Skip to content

Commit

Permalink
feat: make sure all delegate methods happen on the main thread
Browse files Browse the repository at this point in the history
  • Loading branch information
MojtabaHs committed May 20, 2024
1 parent f6579ae commit 081c1bd
Showing 1 changed file with 33 additions and 23 deletions.
56 changes: 33 additions & 23 deletions Sources/iPhoneNumberField/iPhoneNumberField.swift
Original file line number Diff line number Diff line change
Expand Up @@ -256,29 +256,33 @@ public struct iPhoneNumberField: UIViewRepresentable {
var onReturn = { (view: PhoneNumberTextField) in }

@objc public func textViewDidChange(_ textField: UITextField) {
guard let textField = textField as? PhoneNumberTextField else {
return assertionFailure("Undefined state")
}

// Updating the binding
if formatted {
// Display the text exactly if unformatted
text.wrappedValue = textField.text ?? ""
} else {
if let number = textField.phoneNumber {
// If we have a valid number, update the binding
let country = String(number.countryCode)
let nationalNumber = String(number.nationalNumber)
text.wrappedValue = "+" + country + nationalNumber
DispatchQueue.main.async { [weak self] in
guard let self else { return }

guard let textField = textField as? PhoneNumberTextField else {
return assertionFailure("Undefined state")
}

// Updating the binding
if formatted {
// Display the text exactly if unformatted
text.wrappedValue = textField.text ?? ""
} else {
// Otherwise, maintain an empty string
text.wrappedValue = ""
if let number = textField.phoneNumber {
// If we have a valid number, update the binding
let country = String(number.countryCode)
let nationalNumber = String(number.nationalNumber)
text.wrappedValue = "+" + country + nationalNumber
} else {
// Otherwise, maintain an empty string
text.wrappedValue = ""
}
}

displayedText.wrappedValue = textField.text ?? ""
onEditingChange(textField)
onPhoneNumberChange(textField.phoneNumber)
}

displayedText.wrappedValue = textField.text ?? ""
onEditingChange(textField)
onPhoneNumberChange(textField.phoneNumber)
}

public func textFieldDidBeginEditing(_ textField: UITextField) {
Expand All @@ -298,13 +302,19 @@ public struct iPhoneNumberField: UIViewRepresentable {
}

public func textFieldShouldClear(_ textField: UITextField) -> Bool {
displayedText.wrappedValue = ""
onClear(textField as! PhoneNumberTextField)
DispatchQueue.main.async { [weak self] in
guard let self else { return }
displayedText.wrappedValue = ""
onClear(textField as! PhoneNumberTextField)
}
return true
}

public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
onReturn(textField as! PhoneNumberTextField)
DispatchQueue.main.async { [weak self] in
guard let self else { return }
onReturn(textField as! PhoneNumberTextField)
}
return true
}
}
Expand Down

0 comments on commit 081c1bd

Please sign in to comment.