如何在 cocoa 中显示一个弹出窗口,通知 NSTextField 不能为空?
如果用户单击“应用”并且 NSTextField 为空,则会出现一个弹出窗口,提示该字段不能为空。
谢谢
最佳答案
@beryllium 的回答只讲述了故事的一部分。
事实上,要正确验证 Cocoa 中的文本字段输入,您应该使用附加到文本字段单元格的 NSFormatter
,然后在您的 NSTextFieldDelegate
中您应该实现该方法:control:didFailToFormatString:errorDescription:
。在此委托(delegate)方法中,您可以提示用户更正其输入。
您在 NSFormatter
子类中需要做的就是这样:
@implementation RKTextFormatter
- (NSString*)stringForObjectValue:(id)object
{
return (NSString*)object;
}
- (BOOL)getObjectValue:(id*)object forString:(NSString*)string errorDescription:(NSString**)error {
BOOL stringPassesTest = NO;
//put your test here
if(!stringPassesTest)
{
//set the error and return NO
if(error)
*error = [NSError errorWithDomain:@"YourErrorDomain" code:1 userInfo:[NSDictionary dictionaryWithObject:@"It's a bingo" forKey:NSLocalizedDescriptionKey]];
return NO;
}
//otherwise, just assign the string
*object = string;
return YES;
}
@end
您可以将格式化程序分配给您的文本字段,如下所示:
RKTextFormatter* formatter = [[RKTextFormatter alloc] init];
[[textField cell] setFormatter:formatter];
然后在您的 NSTextFieldDelegate
中处理任何无效输入:
- (BOOL)control:(NSControl *)control didFailToFormatString:(NSString *)string errorDescription:(NSString *)error
{
//display an alert, obviously it would be more useful than this
NSAlert* alert = [NSAlert alertWithMessageText:@"You have failed me for the last time" defaultButton:@"Revise Input" alternateButton:nil otherButton:nil informativeTextWithFormat:@"%@",error];
[alert beginSheetModalForWindow:control.window modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
//if you return NO here, the user's input will not be accepted
//and the field will remain in focus
return NO;
}
关于objective-c - 如何在 cocoa 中显示一个弹出窗口,通知 NSTextField 不能为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8354571/