我想在NSOpenPanel期间向用户征求其他信息,但需要在打开面板完成之前验证该信息。例如,我可能希望允许用户在打开的面板选择中添加有关文件的注释,但需要验证该注释是否为空。
我有一个附件视图,其控件绑定到NSObjectController
,其内容对象又绑定到我用来加载附件视图的笔尖的NSViewController的表示对象。所表示的对象具有NSKeyValueCoding
兼容的验证方法(例如-(BOOL)validateKey:error:
)。用户修改控件的值时,将正确处理验证(并通过模式对话框报告违规)。
我的问题是,如果用户未在附件视图中输入任何内容,我将无法弄清楚如何进行验证。例如,假设我在附件视图中有一个文本字段,该文本字段的绑定对象验证了文本长度是否为非零。如果用户输入文本(验证成功),则删除文本,验证失败,并向用户显示错误。但是,如果用户不输入文本,则打开的面板将无错误关闭。在打开面板关闭之前,如何验证文本是否为非零?
最佳答案
您应该将控制器注册为打开面板的委托,然后实现-panel:isValidFilename:
委托方法。从该方法返回NO
可以防止打开的对话框被关闭:
- (BOOL)panel:(id)sender isValidFilename:(NSString *)filename
{
//validate the field in some way, in this case by making sure it's not empty
if([[textField stringValue] length] == 0)
{
//let the user know they need to do something
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Please enter some text."];
[alert addButtonWithTitle:@"OK"];
[alert beginSheetModalForWindow:sender modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
//return NO to prevent the open panel from completing
return NO;
}
//otherwise, allow the open panel to close
return YES;
}
关于cocoa - 在NSOpenPanel附件 View 中验证输入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2203228/