How to restrict UITextField to take only numbers in Swift?

后端 未结 30 919
难免孤独
难免孤独 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 09:11

    Use number formatter

    Swift 4.x

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
          let s = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
          guard !s.isEmpty else { return true }
          let numberFormatter = NumberFormatter()
          numberFormatter.numberStyle = .none
          return numberFormatter.number(from: s)?.intValue != nil
     }
    

提交回复
热议问题