Home > OS >  How to append textfield with "0," if is empty and user clicked on comma/dot separator on a
How to append textfield with "0," if is empty and user clicked on comma/dot separator on a

Time:11-20

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.

CodePudding user response:

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
 }

CodePudding user response:

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"
    }
}
  • Related