How to Enable Only Numeric Digit Keyboard iOS Swift

How to enable Only Numeric Digit Keyboard ios Swift

You can use this function in delegate method.

 public static func convertStringtoArabic(_ paramString: String) -> String {
var finalString: String = paramString
finalString = finalString.replacingOccurrences(of: "٠", with: "0")
finalString = finalString.replacingOccurrences(of: "١", with: "1")
finalString = finalString.replacingOccurrences(of: "٢", with: "2")
finalString = finalString.replacingOccurrences(of: "٣", with: "3")
finalString = finalString.replacingOccurrences(of: "٤", with: "4")
finalString = finalString.replacingOccurrences(of: "٥", with: "5")
finalString = finalString.replacingOccurrences(of: "٦", with: "6")
finalString = finalString.replacingOccurrences(of: "٧", with: "7")
finalString = finalString.replacingOccurrences(of: "٨", with: "8")
finalString = finalString.replacingOccurrences(of: "٩", with: "9")
return finalString
}

And Delegate Method you need to conform

  func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

var newText = NSString(string: textField.text!).replacingCharacters(in: range, with: string)

newText = Preferences.convertStringtoArabic(newText)

// You can use this new text

let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}

How can I show the numeric keyboard by default on iPhone?

The UITextInputTraits protocol (which UITextField conforms to) has a keyboardType property of type UIKeyboardType.

myTextField.keyboardType = UIKeyboardTypeNumberPad;

Allow only Numbers for UITextField input

This is how you might handle the problem on a SSN verification field, you can modify the max length and remove the if statement checking for keyboard type if you need to.

There is also logic to suppress the max length alerts when the user is typing as opposed to pasting data.

Within the context of this code, presentAlert()/presentAlert: is just some basic function that presents a UIAlertController (or a legacy UIAlertView) using the message string passed.

Swift 5

// NOTE: This code assumes you have set the UITextField(s)'s delegate property to the 
// object that will contain this code, because otherwise it would never be called.
//
// There are also some better stylistic approaches in Swift to avoid all the
// nested statements, but I wanted to keep the styles similar to allow others
// to contrast and compare between the two languages a little easier.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

// Handle backspace/delete
guard !string.isEmpty else {

// Backspace detected, allow text change, no need to process the text any further
return true
}

// Input Validation
// Prevent invalid character input, if keyboard is numberpad
if textField.keyboardType == .numberPad {

// Check for invalid input characters
if CharacterSet(charactersIn: "0123456789").isSuperset(of: CharacterSet(charactersIn: string)) {

// Present alert so the user knows what went wrong
presentAlert("This field accepts only numeric entries.")

// Invalid characters detected, disallow text change
return false
}
}

// Length Processing
// Need to convert the NSRange to a Swift-appropriate type
if let text = textField.text, let range = Range(range, in: text) {

let proposedText = text.replacingCharacters(in: range, with: string)

// Check proposed text length does not exceed max character count
guard proposedText.count <= maxCharacters else {

// Present alert if pasting text
// easy: pasted data has a length greater than 1; who copy/pastes one character?
if string.count > 1 {

// Pasting text, present alert so the user knows what went wrong
presentAlert("Paste failed: Maximum character count exceeded.")
}

// Character count exceeded, disallow text change
return false
}

// Only enable the OK/submit button if they have entered all numbers for the last four
// of their SSN (prevents early submissions/trips to authentication server, etc)
answerButton.isEnabled = (proposedText.count == 4)
}

// Allow text change
return true
}

Objective-C

// NOTE: This code assumes you have set the UITextField(s)'s delegate property to the 
// object that will contain this code, because otherwise it would never be called.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Handle backspace/delete
if (!string.length)
{
// Backspace detected, allow text change, no need to process the text any further
return YES;
}

// Input Validation
// Prevent invalid character input, if keyboard is numberpad
if (textField.keyboardType == UIKeyboardTypeNumberPad)
{
if ([string rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet].invertedSet].location != NSNotFound)
{
[self presentAlert: @"This field accepts only numeric entries."];
return NO;
}
}

// Length Validation
NSString *proposedText = [textField.text stringByReplacingCharactersInRange:range withString:string];

// Check proposed text length does not exceed max character count
if (proposedText.length > maxCharacters)
{
// Present alert if pasting text
// easy: pasted data has a length greater than 1; who copy/pastes one character?
if (string.length > 1)
{
// Pasting text, present alert so the user knows what went wrong
[self presentAlert: @"Paste failed: Maximum character count exceeded."];
}

// Character count exceeded, disallow text change
return NO;
}

// Only enable the OK/submit button if they have entered all numbers for the last four
// of their SSN (prevents early submissions/trips to authentication server, etc)
self.answerButton.enabled = (proposedText.length == maxCharacters);

// Allow text change
return YES;
}

Numeric keyboard with decimal

Simply change the keyboard type:

self.someTextField.keyboardType = UIKeyboardType.decimalPad

See the documentation for all the keyboard types.

How to create TextField that only accepts numbers

tl;dr

Checkout John M's solution for a much better way.


One way to do it is that you can set the type of keyboard on the TextField which will limit what people can type on.

TextField("Total number of people", text: $numOfPeople)
.keyboardType(.numberPad)

Apple's documentation can be found here, and you can see a list of all supported keyboard types here.

However, this method is only a first step and is not ideal as the only solution:

  1. iPad doesn't have a numberPad so this method won't work on an iPad.
  2. If the user is using a hardware keyboard then this method won't work.
  3. It does not check what the user has entered. A user could copy/paste a non-numeric value into the TextField.

You should sanitise the data that is entered and make sure that it is purely numeric.

For a solution that does that checkout John M's solution below. He does a great job explaining how to sanitise the data and how it works.

Numeric Keypad and the text input is not visible in iOS screenshot

Sorry for being late actually I found out that it is a security feature which is in action since iOS 13 itself so if you have a keyboard which is numeric and in case you have a text field with secure text masking on then the screenshot captured will not show the keyboard or the textfield contents

Apple Discussion 1

Apple Discussion 2

how to make text field that to accept only 4 digit or numbers in iphone

Sample Code :

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *currentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
int length = [currentString length];
if (length > 4) {
return NO;
}
return YES;
}

Move to next UITextField after entering exactly one numeric digit

Step-1

create the IBOutletCollections and set the tag for each textfield for identify which textfield user tapped.

@IBOutlet var customerIdButtons: [UITextField]!

Step-2

create the common extenson for textfield

extension yourViewController : UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = ((textField.text)! as NSString).replacingCharacters(in: range, with: string)
if newString.count == 1 {
textFieldShouldReturnSingle(textField, newString : newString)
return false
}
return true
}
func textFieldShouldReturnSingle(_ textField: UITextField, newString : String)
{

let nextTag: Int = textField.tag + 1
textField.text = newString
let nextResponder: UIResponder? = textField.superview?.viewWithTag(nextTag)
if let nextR = nextResponder
{
// Found next responder, so set it.
nextR.becomeFirstResponder()
}
else
{
// Not found, so remove keyboard.
textField.resignFirstResponder()
// call your method
}
}

}

finally get the all customer ID , then use

@IBAction func loginButton(_ sender: Any) {
var texts: [String] = []
customerIdButtons.forEach { texts.append($0.text!)}
custID = texts.reduce("", +)
print(custID)
}

How to allow only certain set of numbers in a UITextfield in swift 2.0

Set keyboard type as Number Pad

add this

func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {

if let text = textField.text {

let newStr = (text as NSString)
.stringByReplacingCharactersInRange(range, withString: string)
if newStr.isEmpty {
return true
}
let intvalue = Int(newStr)
return (intvalue >= 0 && intvalue <= 12)
}
return true
}


Related Topics



Leave a reply



Submit