UITextField Should accept number only values

前端 未结 14 1181
有刺的猬
有刺的猬 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:49

    Here is Swift solution:

    In viewDidLoad set the delegate:

    _yourTextField.delegate = self
    
    let _acceptableCharacters = "0123456789."
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    
        if (string.characters.count == 0) {
            return true
        }
    
        if (textField == self._yourTextField) {
            let cs = NSCharacterSet(charactersInString: self._acceptableCharacters)
            let filtered = string.componentsSeparatedByCharactersInSet(cs).filter {  !$0.isEmpty }
            let str = filtered.joinWithSeparator("")
    
            return (string != str)
        }
    
        return true
    }
    

提交回复
热议问题