How can I limit the number of decimal points in a UITextField?

后端 未结 15 2305
说谎
说谎 2020-12-01 05:20

I have a UITextField that when clicked brings up a number pad with a decimal point in the bottom left. I am trying to limit the field so that a user can only place 1 decimal

15条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 05:57

    Swift 4

    The efficient and easy way to avoid multiple decimal points (. or ,) in UITextField:

        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if(string == "," || string == "." ){
    
            if ((textField.text?.contains(","))! || (textField.text?.contains("."))!){
                return false
            }
        }
        return true
    }
    

提交回复
热议问题