krish krish - 5 months ago 60
Objective-C Question

Allowing single digit in UITextField in iOS

I have a

Verification ViewController
, I get 4 digit verification code by SMS and I need to enter those code to login , I have created the
ViewController
like this



As you can see four
UITextField
s , I need to allow only single digit for each
UITextField
,

What i tried : I was trying to use
shouldChangeCharactersInRange:method:
, but its not getting called ,I don't know whats wrong, i think because
UITextField
s are in
UITableView
so it is not working .

Can Anyone suggest me how to solve this issue.

thanks

Answer

you can change the textfield like this by using delegate function of text field and initially you need to set the delegate and tag of each text field as 1,2,3,4

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

Here is the Swift 2.0 Code for the same:

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