I am currently developing an app where user needs to input fuel price in 0,00 format where after first digit shows comma and it is limited only to input 3 digits. Does anybody have solution?
Asked
Active
Viewed 51 times
1 Answers
0
Add the following objc
function inside your UIViewController
class:
@objc func format_textfield(_ sender:UITextField){
var str:String = sender.text!
if str.count>0 && Array(str)[0] == ","{
sender.text = String(str.suffix(from: str.index(str.startIndex,offsetBy: 1)))
str = sender.text!
}
if str.count > 4 {
sender.text = String(str.prefix(4))
}else if str.count > 1 && Array(str)[1] != ","{
sender.text = String(str[..<str.index(str.startIndex, offsetBy: 1)])+","+String(str[str.index(str.startIndex, offsetBy: 1)...])
}
}
Then, add the function as a target for your UITextField
like this (this can be done in the viewDidLoad()
method):
textField.addTarget(self, action: #selector(format_textfield(_:)), for: .editingChanged)

FelipeCruzV10
- 426
- 6
- 13
-
Great! Nice solution but just one thing , when I want to delete I can not delete all charachters , example I texted 1,99 but when I delete it with numberic pad keyboard it stays by 1, could you please check it why? – Petar Ivic Jun 01 '21 at 22:17
-
Give me some minutes and I'll edit my answer with a better solution :) – FelipeCruzV10 Jun 01 '21 at 22:18
-
Ok , nice to hear that :) – Petar Ivic Jun 01 '21 at 22:50
-
Done! It can still be improved but I think it works well enough. Maybe you can make the improvements. Things to improve: when you delete the first number, the text cursor is moved to the right. – FelipeCruzV10 Jun 01 '21 at 22:53
-
Works like a charm I appreciate it :) – Petar Ivic Jun 01 '21 at 23:04
-
Also, allow the user to only add numbers. Because, at this moment, the user is able to add letters and symbols. You can set the keyboard type to numeric only. – FelipeCruzV10 Jun 01 '21 at 23:26
-
Yes, that is what I did – Petar Ivic Jun 01 '21 at 23:35