简体   繁体   中英

UIAlertView showing unintentionally after each number entry

Here is a problem with my textfields.

-(void)textFieldTextDidChange:(NSNotification *)notif
{
    event.eventName = eventTextField.text;
    event.eventPlace = eventPlaceTextField.text;
    event.eventWinery = wineryTitleLabel.text;
    int vintageVal = [vintageTextField.text intValue];
    if([vintageTextField.text length]>0 && [vintageTextField.text length] == 4)
    {
        event.eventVintage = vintageVal;
    }
    else 
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"!!! MESSAGE !!!"
                 message:@" Enter the Valid year in Format YYYY"
                 delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show]; 
        [alert release];
        return;
    }
}

If the user enters the year with four digits then only it should be saved into event.eventVitage But when entering data I'm getting the alert view every single number.

What am I doing wrong?

Your problem is with your if statement.

if([vintageTextField.text length]>0 && [vintageTextField.text length] == 4)

In the && part of it you are checking to see if the length is 4. If the lenth is not 4 then the else is called. You need to check if the length is less than or equal to 4 <= and so the alert will only show when the length is greater than 4-------------------------------------------------------------------------------------!

if([vintageTextField.text length]>0 && [vintageTextField.text length] <= 4)

Hope this helps and have fun coding

    if([vintageTextField.text length]>0 && [vintageTextField.text length] == 4)
{
    event.eventVintage = vintageVal;
}
else 
{....

This says: if your textString is 4 (the larger than 0 is redundant here..) this mean that when it is 1-2-3 it will run the else code.

In situations like this I often either gray the text out until the user has entered enough digits or disable the "save" button. If you don't have any way for the user to indicate that he is done typing, it is hard to foresee.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM