Adnan
Adnan

Reputation: 8729

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];        
      }
  }

Upvotes: 0

Views: 1352

Answers (3)

Damo
Damo

Reputation: 12890

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];
    }

Upvotes: 3

graver
graver

Reputation: 15213

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

Upvotes: 2

TompaLompa
TompaLompa

Reputation: 949

I assume that addText is your tesxField so you need to set the condition [addtake.text length] == 0 aswell.

Upvotes: 1

Related Questions