【问题标题】:How to properly use delegation for NSTextField如何正确使用 NSTextField 的委托
【发布时间】:2014-02-21 03:18:14
【问题描述】:

我正在尝试为 NSTextField 对象实现一个委托,以便我可以实时检测用户输入并就该特定字段中不允许输入提供一些反馈。 特别是,我想从 JavaScript 模拟 onChange() 方法,实时检测用户输入,如果它正在写入不支持的值,则向他显示警告。

即该应用程序有一个文本字段,它只接受从 0 到 255 的数值(如 RGB 值),我想知道用户何时写入的不是数值或超出范围的值,以便立即向他显示警告消息或更改文本字段背景颜色,只是一个视觉提示,让他知道输入是错误的。

就像你在上面的图片中看到的那样,每次用户在文本字段中输入禁止值时,我都想显示一个警告标志。

我已经阅读了很多Apple's documentation,但我不明白要实现哪个委托(NSTextFieldDelegateNSTextDelegateNSTextViewDelegate),而且我不知道如何在其中实现它我的AppDelegate.m 文件以及使用哪种方法以及如何获得用户编辑的通知。

现在,我已经在我的 init 方法中使用类似 [self.textField setDelegate:self]; 的方式设置了 Delegate,但我不明白如何使用它或实现哪种方法。

【问题讨论】:

  • 我建议您使用NSNumberFormatter 来处理这类事情。界面生成器的侧边栏中甚至还有一个带有数字格式化程序的NSTextField
  • 感谢您的推荐,但我的格式化程序已经可以正常工作了,但为了用户友好性问题,我需要实施视觉警告。

标签: objective-c macos nstextfield


【解决方案1】:

我使用此问题中发布的信息找到了解决方案...Listen to a value change of my text field

首先我必须在 AppDelegate.h 文件中声明 NSTextFieldDelegate

@interface AppDelegate : NSObject <NSApplicationDelegate, NSTextFieldDelegate>

之后,我必须为要修改的 NSTextField 对象实例化委托,同时用户在 AppDelegate.m 文件中更新它。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self.textField setDelegate:self];
}

最后,我实现了使用我想要设置的更改来检测字段编辑的方法。

- (void)controlTextDidChange:(NSNotification *)notification {
    NSTextField *textField = [notification object];
    if ([textField doubleValue] < 0 | [textField doubleValue] > 255) {
        textField.textColor = [NSColor redColor];
    }
}

- (void)controlTextDidEndEditing:(NSNotification *)notification {
    NSTextField *textField = [notification object];
    if ([textField resignFirstResponder]) {
        textField.textColor = [NSColor blackColor];
    }
}

【讨论】:

    【解决方案2】:

    让你的类符合NSTextFieldDelegate 协议。它必须是那个协议,因为在documentation 中它说明了委托所遵循的协议类型。

    @interface MyClass : NSObject

    并实现委托的方法(只需将它们添加到您的代码中)。示例

    - (BOOL)control:(NSControl *)control textShouldBeginEditing:(NSText *)fieldEditor
    {
    }
    

    编辑:

    我认为在您的情况下,最好将 TextField 替换为 TextView 并使用 NSTextViewDelegate,在委托中,您最感兴趣的方法应该是

    - (BOOL)textView:(NSTextView *)aTextView shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString
    {
        BOOL isValid = ... // Check here if replacementString is valid (only digits, ...)
        return isValid; // If you return false, the user edition is cancelled
    }
    

    【讨论】:

    • 您能否更具体地说明我应该如何使用这个textShouldBeginEditing 方法,因为这是我正在尝试使用的方法,但我不明白如何使用。我在 Cocoa 开发方面还是太新了(到目前为止只有 2 周)。
    • 我无法确切告诉你该怎么做,你想完成什么?
    • 我已经用一些图片来解释我的想法更新了我的问题。
    • @DaveGomez 更新答案
    猜你喜欢
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多