-4

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?

1 Answers1

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