Using FirstResponder with Text Validation Question for iPhone SDK
I am trying to validate my text fields, so that if there is an issue the user input it will catch it and show an Alert (got that part) and not go to the next field (can't get that part). Any thoughts on what I'm doing wrong with this?
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == txtUserName)
{
[txtUserName2 becomeFirstResponder];
}
else if (textField == txtUserN开发者_开发知识库ame2)
{
[txtUserName3 becomeFirstResponder];
}
else if (textField == txtUserName3)
{
[txtUserName4 becomeFirstResponder];
}
else if (textField == txtUserName4)
{
[txtUserName5 becomeFirstResponder];
}
return NO;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if (textField == txtUserName)
{
NSString *userNameOne = txtUserName.text;
double numOne = [userNameOne intValue];
if(numOne < 40 || numOne > 100)
{
//play sound and vibrate for alert
NSString *bonkSoundFile = [[NSBundle mainBundle] pathForResource:@"alertSound" ofType:@"mp3"];
NSURL *fileURL = [NSURL fileURLWithPath:bonkSoundFile];
SystemSoundID bonkSoundID;
AudioServicesCreateSystemSoundID( (CFURLRef) fileURL, &bonkSoundID);
AudioServicesPlaySystemSound(bonkSoundID);
AudioServicesPlaySystemSound (kSystemSoundID_Vibrate); //vibrate
//show alert
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Age Error"
message:@"Your age must be at least 40 years old and less than 100 years old"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
//if there is an error, then don't go to next field but make current textField the //FirstResponder
[txtUserName becomeFirstResponder];
}
}
and so on for a total of five fields. I'm just not sure what I'm doing wrong...
Have you tried putting the validation code into
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
And having it return NO when you don't want to continue onto the next field?
精彩评论