0

我正在尝试编写一个 NSAlert,当某些 NSTextFields 为空时出现。我有 3 个 NSTextField,我想要一个 NSAlert 来显示列表中哪个 TextField 为空。我可以为一个文本字段执行此操作,但我如何编码空的 NSTextFields 出现在 Alert 中?如果 Altert 中的一个 Textfield 为空,则应显示“TextField 1 is empty”。如果字段 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");
    }];
} 
4

2 回答 2

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");}];
      }
    }
    
于 2015-09-07T16:04:46.480 回答
0

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

我在代码中的话:

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为空。

于 2015-09-07T16:44:10.340 回答