SteBra
SteBra

Reputation: 4247

How to set focus on the next UITextView, after user types in 2 chars in the first one

I have several text fields, where the user can input some data. every text field accepts 2 digit numbers as parameters. User experience wise, it's awesome if the focus is put to another text view, right after the number has been typed into the current UITextView.

Let's say I have 2 UITextViews - txt1 and txt2. the user clicks on the txt1, keyboard appears and the user types in 2 digit number.

Where in my code should i check, how many characters are input in a text view?

I assume that I need some listener or something?

When in that listener I get the notification that 2digit number is typed in, I should call

[_txt2 becomeFirstResponder];

This is just an idea, I dont have a chance to test it, as I'm not really sure how to setup the mentioned listener.

Any ideas?

Upvotes: 0

Views: 1296

Answers (2)

Vignesh
Vignesh

Reputation: 170

Simple. You can use UITextfield delegate methods to achieve this.. First declare textfield delegate methods in your .h or .m file..

@interface ViewController:UIViewController< UITextFieldDelegate >

Next,use the below mentioned delegate method to check the number of characters in your textfield (in your case, it is 2)

    - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string   
    {
          if (textfield.text.length==2)
          {
            [textfield2 becomesFirstResponder];
          }
          return YES;
    }

3) you can use a number of if-else loops as per your requirement.

Upvotes: 2

Brett DiDonato
Brett DiDonato

Reputation: 1952

Use the UITextViewDelegate method - (void)textViewDidChange:(UITextView *)textView. This entails adding the delegate to your view controller:

@interface ViewController : UIViewController <UITextViewDelegate>

Assigning the delegate to your text view:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.textView.delegate = self;
}

And then defining the delegate method:

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length == 2) {
        // Change first responder here
    }
}

Upvotes: 2

Related Questions