如果TextFields为空,则将“信息性文本”添加到Alert

时间:2015-09-07 15:42:46

标签: objective-c cocoa if-statement nsalert

我正在尝试编写NSAlert代码,当某些NSTextField为空时出现。 我有3个NSTextFields,我想有一个NSAlert,它在列表中显示哪个TextField为空。我可以在一个文本字段中执行此操作,但是如何编写空的NSTextFields出现在警报中?如果Altert中的一个Textfield为空,则表示“TextField 1为空”。如果字段1和2为空,则应显示“TextField 1为空”,并在第二行“TextField 2为空”。

这是我的代码:

if ([[TextField1 stringValue] length] == 0) {
    NSAlert* alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:@"OK"];
    [alert setMessageText:@"Error"];
    [alert setInformativeText:@"TextField 1 is empty"];
    [alert beginSheetModalForWindow:[self.view window] completionHandler:^(NSInteger result) {
        NSLog(@"Success");
    }];
} 

2 个答案:

答案 0 :(得分:1)

您可以通过通知自动获取信息。

  • 将标签1,2,3分配给文本字段。
  • 将Interface Builder中所有文本字段的委托设置为要在其中显示警报的类。
  • 实施此方法

    - (void)controlTextDidChange:(NSNotification *)aNotification
    {
      NSTextField *field = [aNotification object];
      if ([[field stringValue] length] == 0) {
        NSInteger tag = field.tag;
        NSAlert* alert = [[NSAlert alloc] init];
        [alert addButtonWithTitle:@"OK"];
        [alert setMessageText:@"Error"];
        [alert setInformativeText:[NSString stringWithFormat:@"TextField %ld is empty", tag]];
        [alert beginSheetModalForWindow:[self.view window] completionHandler:^(NSInteger result) {NSLog(@"Success");}];
      }
    }
    

答案 1 :(得分:0)

我会链接if语句以获得所需的结果。 设置一个空字符串并逐个检查每个textField。如果字符串为空,则将错误行添加到字符串中。不要忘记在追加字符串后添加换行符。

我在代码中的说法:

NSString* errorMessage = @"";

if ([[TextField1 stringValue] length] == 0) {
    errorMessage = @"TextField 1 is empty.\n";
}

if ([[TextField2 stringValue] length] == 0) {
    errorMessage = [errorMessage stringByAppendingString:@"TextField 2 is empty.\n"];
}   

if ([[TextField3 stringValue] length] == 0) {
    errorMessage = [errorMessage stringByAppendingString:@"TextField 3 is empty."];
}

if (![errorMessage isEqualToString:@""]) {
    NSAlert* alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:@"OK"];
    [alert setMessageText:@"Error"];
    [alert setInformativeText:errorMessage];
    [alert beginSheetModalForWindow:[self.view window] completionHandler:^(NSInteger result) {
        NSLog(@"Success");
    }];
}

这样您就可以获得动态输出,具体取决于NSTextField为空。

相关问题