Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Separator "-" in text field in Swift iOS [duplicate]

I would like to add "-" between 4 numbers when user is typing in PinNo text field.
For example, 1234 - 5678 - 9932

enter image description here

like image 200
May Phyu Avatar asked Dec 07 '25 14:12

May Phyu


1 Answers

// try like this

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool 
{
    var strText: String? = textField.text
   if strText == nil {
     strText = ""
   }
 strText = strText?.stringByReplacingOccurrencesOfString("-", withString:"")
 if strText!.characters.count > 1 && strText!.characters.count % 4 == 0 && string != "" {
    textField.text = "\(textField.text!)-\(string)"
     return false
 }

 return true
}
like image 126
Satyanarayana Avatar answered Dec 10 '25 03:12

Satyanarayana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!