Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

ios - How to check text field input at real time?

I am writing validation for my textfield, I found something interesting that whether I can check how many digits I am typing into the textfield at real time. My text field input must be 8 digit number. So I want to change the text inside the text field to green colour when I reach 8 digit and change colour when it's not.

How can I do that? Please help me, thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using -textField:shouldChangeCharactersInRange:replacementString: is probably a bad solution because it fires before the text field updates. This method should probably be used when you want to change the text of the text field before the keyboard automatically updates it. Here, you probably want to simply use target-action pairing when editing value changes:

[textField addTarget:self action:@selector(checkTextField:) forControlEvents:UIControlEventEditingChanged];

Then, in - (void)checkTextField:(id)sender, try this:

UITextField *textField = (UITextField *)sender;
if ([textField.text length] == 8) {
    textField.textColor = [UIColor greenColor]; // No cargo-culting please, this color is very ugly...
} else {
    textField.textColor = [UIColor blackColor];
    /* Must be done in case the user deletes a key after adding 8 digits,
       or adds a ninth digit */
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...