objective-c - 如何在 cocoa 中显示一个弹出窗口,通知 NSTextField 不能为空?

标签 objective-c cocoa

如何在 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/

相关文章:

选择取消按钮错误后的 iOS 11 UIImagePickerController

iphone - 将 xcode 集成到 mopub

ios - 如何在UILocalNotification警报正文中指定相对时间(即“在X分钟内开始”)?

cocoa - 我如何知道附件属性何时添加到我的 NSTextView 中?

objective-c - 将集群类作为单例?

objective-c - xib 中的预处理器指令?

iphone - 无法设置 NSString 属性,崩溃

cocoa - 窗口顶部的 iTunes 或 Xcode 风格信息框

cocoa - 使用 KVO 时出现异常

objective-c - 如何让 NSSearchField 在自动完成时发送操作?