如何在可可中显示通知NSTextField的弹出窗口不能为空?
如果用户单击"应用"并且NSTextField为空,则应显示弹出窗口,表示该字段不能为空.
谢谢
@beryllium的答案只讲述了故事的一部分.
事实上,要正确验证Cocoa中的文本字段输入,您应该使用NSFormatter附加到文本字段单元格,然后在您NSTextFieldDelegate应该实现方法:control:didFailToFormatString:errorDescription:.在此委托方法中,您可以提示用户更正其输入.
您在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
Run Code Online (Sandbox Code Playgroud)
您可以将格式化程序分配给文本字段,如下所示:
RKTextFormatter* formatter = [[RKTextFormatter alloc] init];
[[textField cell] setFormatter:formatter];
Run Code Online (Sandbox Code Playgroud)
然后在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;
}
Run Code Online (Sandbox Code Playgroud)
如果用户单击"应用"并且NSTextField为空,则应显示弹出窗口,表示该字段不能为空.
拜托,请不要这样做.你可以比那更聪明.
不要花时间编写警告对话框来处理"意外"情况,而是投入创建一种方法来防止问题首先发生:保持Apply按钮禁用,直到在文本字段中输入了正确的值.
另外,@Rob Keniger如上所述,您应该考虑使用NSFormatters来验证输入以确保它是合适的类型.
| 归档时间: |
|
| 查看次数: |
2395 次 |
| 最近记录: |