How to restrict UITextField to take only numbers in Swift?

后端 未结 30 934
难免孤独
难免孤独 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:03

    Here's an cleaner solution:

     guard CharacterSet(charactersIn: "123456789").isSuperset(of: CharacterSet(charactersIn: string)) else {
         return false
     }
     return true
    

    For decimals just add ., example 123456789.

提交回复
热议问题