Search code examples
iosswiftuitextfieldseparator

Add Separator "-" in text field in Swift iOS


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


Solution

  • // 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
    }