简体   繁体   中英

Show UIAlert if UITextField is empty

All I want to do, If there is nothing on UITextField , application will show an alert. I don't understanding what's wrong I'm doing. here is my code:

- (IBAction)Calculate:(id)sender {
    /*If there is nothing on textfield, it will show an alert*/

    if ([addtake.text length] && [Subtake.text length] == 0) 
    {

            UIAlertView *myAlert = [[UIAlertView  alloc]initWithTitle:@"Alert"message:@"Empty   TextField not allowed" delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles: nil];    
            [myAlert show];
    }

    else{

            NSString *Adding =[addtake text];
            NSInteger number = [Adding intValue]; /*Converting String to int*/
            NSInteger new = 5 + number;
            NSString *newString = [NSString stringWithFormat:@"%d",new];
            [myAdd setText:newString];
            /*Subtruct*/
            NSString *Subtruct =[Subtake text];
            NSInteger SubNumber = [Subtruct intValue];
            NSInteger newSub = 10 - SubNumber;
            NSString *newSubString = [NSString stringWithFormat:@"%d",newSub];
            [mySub setText:newSubString];

            [addtake resignFirstResponder]; 
            [Subtake resignFirstResponder];        
      }
  }

Try making each sub-clause in your if statement explicit - if only for readability...

I would use logical OR, not logical AND in your test. So that if either text field is empty the alert would show

    if ((![addtake.text length]) || (![Subtake.text length])) 
    {

            UIAlertView *myAlert = [[UIAlertView  alloc]initWithTitle:@"Alert"message:@"Empty   TextField not allowed" delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles: nil];    
            [myAlert show];
    }
if ([addtake.text length] == 0 && [Subtake.text length] == 0) 

我假设addText是您的tesxField,所以您还需要设置条件[addtake.text length] == 0。

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