How to restrict UITextField to take only numbers in Swift?

后端 未结 30 897
难免孤独
难免孤独 2020-12-04 08:40

I want the user to only enter numeric values in a UITextField. On iPhone we can show the numeric keyboard, but on iPad the user can switch to any keyboard.

30条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 08:56

    Set KeyboardType Property :- Number Pad TextField Delegate please write below code

      func textField(_ textField: UITextField, shouldChangeCharactersIn 
      range: NSRange, replacementString string: String) -> Bool {
    
        if textField.text?.count == 0 && string == "0" {
            return false
        }
        return string == string.filter("0123456789".contains)
    }
    

    Number should not start from 0 and entered number +ve.

提交回复
热议问题