UITextField Should accept number only values

前端 未结 14 1238
有刺的猬
有刺的猬 2020-12-08 09:50

I have UITexfields i want that it should accept only number other shows alert that enter a numeric value. I want that motionSicknessTextFiled should only accept number

14条回答
  •  春和景丽
    2020-12-08 10:31

    Here is the working example for swift 4

    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        // Allow Backspace
        if string.count == 0 {
            return true
        }
    
        // Allow Only Valid Decimal Numbers
        if let textFieldText = textField.text   {
    
            let finalText = (textFieldText as NSString).replacingCharacters(in: range, with: string)
            if Double(finalText) != nil {
                return true
            }
        }
        return false
    }
    

提交回复
热议问题