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

May Phyu
- 895
- 3
- 23
- 47
1 Answers
7
// 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
}

Satyanarayana
- 1,059
- 6
- 16
-
Error : value of type 'String?' has no member "characters" shows. – May Phyu Jun 07 '16 at 08:33
-
No error now. Spelling of "character" is wrong. Whatever thank you. :) – May Phyu Jun 07 '16 at 08:42
-
ohh, all the above code typed here only , okay fine i will edit that answer :), anyway is it working for you – Satyanarayana Jun 07 '16 at 08:48
-
not working well. When I type , it shows "Optional -\( 123" like that. – May Phyu Jun 07 '16 at 09:18
-
do one thing change this line like this textField.text = "\(textField.text)-\(string)" as textField.text = "\(textField.text!)-\(string)" – Satyanarayana Jun 07 '16 at 09:28
-
i edited the answer , take code from there , then it will work for u – Satyanarayana Jun 07 '16 at 09:29
-
Yes. It's working now. Thank you very much :). One more I want to add is that to remove "-" from beginning. – May Phyu Jun 07 '16 at 09:40
-
if strText!.characters.count != 0 { txtPinNo.text = "\(txtPinNo.text!)-\(string)" return false } – May Phyu Jun 07 '16 at 09:41
-
for this hyphen(-) is added for every charecter what you are typing – Satyanarayana Jun 07 '16 at 09:44
-
so, don't add if strText!.characters.count != 0 { txtPinNo.text = "(txtPinNo.text!)-(string)" return false } – Satyanarayana Jun 07 '16 at 09:46
-
for that i extended that condition with strText!.characters.count > 1 && so no issue, so that problem wont come now – Satyanarayana Jun 07 '16 at 09:48
-
once check the answer – Satyanarayana Jun 07 '16 at 09:49
-
It is working well now. Thanks a lot to you. :) – May Phyu Jun 07 '16 at 10:03
-
for swift 3 use `strText?.replacingOccurrences(of: "-", with: "")` instead of `strText?.stringByReplacingOccurrencesOfString("-", withString:"")` – Amir Shabani Jun 06 '17 at 08:21