Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 258 Vote(s) - 3.46 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to restrict UITextField to take only numbers in Swift?

#1
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.

Is there any way to restrict user to enter only numeric values in a `UITextField`?

----

**Note:** This is an old question with many many answers. More than one third of the posted answers are wrong. Even some of the highly upvoted answers are wrong. Please, DO NOT post a new answer unless it somehow finds a vastly improved way to solve this question in a way that isn't shown already. Make sure your answer works in all circumstances. It must work for both iPhones and iPads. It must work when a user pastes text into the text field. It must work if the user has an external keyboard. It must work if the user changes the text selection in the text field before typing or pasting text. It must properly support decimal numbers (one decimal separator appropriate for the user's locale).
Reply

#2
When copying and pasting, there is a possibility of accidentally entering duplicate decimal points in numeric values. The following solution ensures that only numeric values and a single decimal point are allowed.


```
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowedCharacterSet = CharacterSet(charactersIn: "0123456789.")
let replacementStringCharacterSet = CharacterSet(charactersIn: string)
let isNumeric = allowedCharacterSet.isSuperset(of: replacementStringCharacterSet)

if !isNumeric {
return false
}

let currentText = textField.text ?? ""

if string.contains(".") {
// Check if the text already contains a dot
let containsDot = currentText.contains(".")
if containsDot {
return false
}
}

return true
}

```
Reply

#3
**iPhone**

In whatever UITextField you're getting these values from, you can specify the kind of keyboard you want to appear when somebody touches inside the text field.

E.G. a numeric-only keyboard.

Like this screenshot:

[![enter image description here][1]][1]


[1]:


**iPad**

The iPad does not support the numeric keyboard, so your options are to either not support the iPad, validate the field post submit, or follow one of the other suggestions here to create same behaviors while running on an iPad.
Reply

#4
In case someone wants only "English" letters or numbers, there is ACCII Capable option in the Keyboard type list in the Attributes Inspector
[![enter image description here][1]][1]


[1]:
Reply

#5
//instead of these you can simply change your keyboard to number type

yourtextfield.keyboardType = UIKeyboardType.numberPad
Reply

#6
### Solution for swift 3.0 and above
```swift
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
```
Reply

#7
An approach that solves both decimal and Int:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentText = textField.text
let futureString = currentText.substring(toIndex: range.location) + string + currentText.substring(fromIndex: range.location + range.length)

if futureString.count == 0 {
return true
}

if isDecimal {
if let numberAsDouble = Double(futureString), numberAsDouble.asPrice.count >= futureString.count {
return true
}
} else if let numberAsInt = Int(futureString), "\(numberAsInt)".count == futureString.count {
return true
}

return false
}
Reply

#8
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.
Reply

#9
In swift 4.1 and Xcode 9.4.1

Add **UITextFieldDelegate** to your class

class YourViewController: UIViewController, UITextFieldDelegate

Then write this code in your **viewDidLoad()**

mobileNoTF.delegate = self

Write this textfield delegate function

//MARK - UITextField Delegates
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//For mobile numer validation
if textField == mobileNoTF {
let allowedCharacters = CharacterSet(charactersIn:"+0123456789 ")//Here change this characters based on your requirement
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
return true
}
Reply

#10
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.`
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through