I want to add hyphen after 3rd character.
I want to change like this.
If I input 1111111 in textfield, it automatically change to 111-1111
@State var postalCode = ""
TextField("PostalCode", text: $postalCode)
.onReceive(Just(postalCode)) { _ in
if postalCode.count > 8 {
postalCode = String(postalCode.prefix(8))
}
else if postalCode.count == 3{
postalCode = postalCode + "-"
}
}
But this above code doesn't work when I delete the previous characters.
I mean if I find wrong number, I can't go back before 3rd character.
The textfield sticks to 111-. I could not manipulate it.
And I found a swift storyboard sample code.
class CreateViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var deckCodeLabel: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
deckCodeLabel.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (string == "") { return true }
if (textField.text?.count == 3) {
textField.text = (textField.text)! + string + "-"
return false
}
textField.text = String(textField.text!.prefix(8))
return true
}
But I don't know how to change it to my code in SwiftUI
.onChangebut it might not fix your problem because text fields are buggy in SwiftUI so you might want to just wrap your UIKit implementation inUIViewRepresentable.