如果UITextField为空,则显示UIAlert

时间:2012-05-18 07:41:42

标签: iphone ios ios5

我想做的一切,如果UITextField上没有任何内容,应用程序将显示警告。我不明白我在做什么。这是我的代码:

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

3 个答案:

答案 0 :(得分:3)

尝试将if语句中的每个子句都显式化 - 如果只是为了可读性......

我会在你的测试中使用逻辑OR,而不是逻辑AND。因此,如果任一文本字段为空,则警报将显示

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

我认为addText是你的tesxField所以你需要设置条件[addtake.text length] == 0。