Allowing Single Digit in Uitextfield in iOS

Allowing single digit in UITextField in iOS

You can change the text field like this by using the delegate function of the text field. Initially, you need to set the delegate and the tag of each text field.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ((textField.text.length >= 1) && (string.length > 0))
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (! nextResponder)
nextResponder = [textField.superview viewWithTag:1];

if (nextResponder)
// Found next responder, so set it.
[nextResponder becomeFirstResponder];

return NO;
}
return YES;
}

Swift 2

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// On inputing value to textfield
if (textField.text?.characters.count < 1 && string.characters.count > 0){
let nextTag = textField.tag + 1;

// get next responder
var nextResponder = textField.superview?.viewWithTag(nextTag);

if (nextResponder == nil){
nextResponder = textField.superview?.viewWithTag(1);
}
textField.text = string;
nextResponder?.becomeFirstResponder();
return false;
}
else if (textField.text?.characters.count >= 1 && string.characters.count == 0){
// on deleting value from Textfield
let previousTag = textField.tag - 1;

// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag);

if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1);
}
textField.text = "";
previousResponder?.becomeFirstResponder();
return false;
}
return true;
}

Swift 4

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

if textField.text!.count < 1 && string.count > 0{
let nextTag = textField.tag + 1

// get next responder
var nextResponder = textField.superview?.viewWithTag(nextTag)

if (nextResponder == nil){

nextResponder = textField.superview?.viewWithTag(1)
}
textField.text = string
nextResponder?.becomeFirstResponder()
return false
}
else if textField.text!.count >= 1 && string.count == 0{
// on deleting value from Textfield
let previousTag = textField.tag - 1

// get next responder
var previousResponder = textField.superview?.viewWithTag(previousTag)

if (previousResponder == nil){
previousResponder = textField.superview?.viewWithTag(1)
}
textField.text = ""
previousResponder?.becomeFirstResponder()
return false
}
return true

}

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;
}

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
}

How can I enable the UITextField to have only one text/number and navigate through multiple `UITextField`s using Next / Done Button

you can do this by using textfield delegate Method you can set tags to each text field in sequence like 1,2,3…. now in shouldChangeCharactersInRange

Method right logic that make next box to become first responder when you type one text/number in text box.

like given below

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

if ((textField.text.length >= 1) && (string.length > 0))
{

NSInteger nextText = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextText];
if (! nextResponder)
nextResponder = [textField.superview viewWithTag:1];

if (nextResponder)
// Found next responder, so set it.
[nextResponder becomeFirstResponder];

return NO;
}
return YES;
}

Edit:

If you want to Display enter text alos on jump of textfield you can add these lines after [nextResponder becomeFirstResponder]

add these lines given below

     UITextField nextTextfield= (UITextField) [textField.superview viewWithTag:nextText]; 
[nextTextfield setText:string];

EDIT for resign responder for keyboard in last textfield.

If you want resign responder for last textfield 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.tag<10) {

if ((textField.text.length >= 1) && (string.length > 0))
{

NSInteger nextText = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextText];
if (! nextResponder)
[textField resignFirstResponder];
// nextResponder = [textField.superview viewWithTag:1];

if (nextResponder){
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
UITextField *nextTextfield= (UITextField*) [textField.superview viewWithTag:nextText];
if (nextTextfield.text.length<1) {
if(nextTextfield.tag==4){
[nextTextfield setText:string];
[nextTextfield resignFirstResponder];
}else{
[nextTextfield setText:string];
}

}

return NO;

}

}
}

return YES;

}

This in this we check for last text tag here i check for 4 tag value u put ur last textfiedl tag in condition when u enter value for last textfield it will resign keyboard. hope this will help you.

Limit UITextField input to numbers in Swift

You can use UITextFieldDelegate’s shouldChangeCharactersInRange method to limit the user's input to numbers:

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

// Create an `NSCharacterSet` set which includes everything *but* the digits
let inverseSet = NSCharacterSet(charactersInString:"0123456789").invertedSet

// At every character in this "inverseSet" contained in the string,
// split the string up into components which exclude the characters
// in this inverse set
let components = string.componentsSeparatedByCharactersInSet(inverseSet)

// Rejoin these components
let filtered = components.joinWithSeparator("") // use join("", components) if you are using Swift 1.2

// If the original string is equal to the filtered string, i.e. if no
// inverse characters were present to be eliminated, the input is valid
// and the statement returns true; else it returns false
return string == filtered
}

Updated for Swift 3:

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

// Create an `NSCharacterSet` set which includes everything *but* the digits
let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted

// At every character in this "inverseSet" contained in the string,
// split the string up into components which exclude the characters
// in this inverse set
let components = string.components(separatedBy: inverseSet)

// Rejoin these components
let filtered = components.joined(separator: "") // use join("", components) if you are using Swift 1.2

// If the original string is equal to the filtered string, i.e. if no
// inverse characters were present to be eliminated, the input is valid
// and the statement returns true; else it returns false
return string == filtered
}

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)
}

Not allowing user to enter the number 1 as the first digit in a UITextField

I have modified the example you want to use as per your need, you can check it out

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==self.testTextField&&range.location==0)
{
if ([string hasPrefix:@"1"])
{
return NO;
}
}

return YES;
}

UITextField Should accept number only values

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:

numeric only keyboard will appear

This is easily set when working with the XIB and the Interface Builder built into Xcode, but if you want to understand this programmatically, take a look at Apple's UITextInputTraits protocol reference page, specifically the keyboardType property information.

To filter out punctuations, set the textfield's delegate and set up the shouldChangeCharactersInRange method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:textField.text];

    BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
    return stringIsValid;
}


Related Topics



Leave a reply



Submit