UITextField Should accept number only values

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

    swift 4

    This allows only number input and you can also set character limitation

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
      let compSepByCharInSet = string.components(separatedBy: aSet)
      let numberFiltered = compSepByCharInSet.joined(separator: "")
    
      if string == numberFiltered {
        let currentText = textField.text ?? ""
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
        return updatedText.count <= 10
      } else {
        return false
      }
    }
    

提交回复
热议问题