-1

How could I detect if user clicked on comma or decimal numpad, so if a textfield is empty and the user clicked on comma or dot decimal separator on a decimal numpad I would like to append textfield text with "0,"? I know that I could use uitapgesture on the whole textfield, but that's not what I need.

karel
  • 5,489
  • 46
  • 45
  • 50
miki
  • 75
  • 9

2 Answers2

2
override func viewDidLoad() {

        super.viewDidLoad()
        yourTextFiled.delegate = self


}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        
        if (string == "." || string == ",") && textField.text?.count == 0{
    
                textField.text = "0"
        }
        
        return true
 }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Noman Umar
  • 369
  • 1
  • 7
0

you can try Like Below Also

override func viewDidLoad() {
    super.viewDidLoad()
    yourTextField.addTarget(self, action: #selector(functionName), for: .editingChanged)
}
 
@objc func functionName(){
    guard let textFieldValue = yourTextField.text else {return}
    if yourTextField.count != 0 && (yourTextField == "," || yourTextField == "."){
        yourTextField.text = "0"
    }
}
Gowtham
  • 385
  • 1
  • 11