2014-02-20 63 views
0

我试图实现NSTextField对象的代理,以便我可以实时检测用户输入并提供有关在该特定字段中没有允许输入的反馈。 特别是,我想模拟来自JavaScript的onChange()方法,实时检测用户输入,并在其写入不支持的值时显示警告。如何正确使用NSTextField的代理

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

enter image description here enter image description here

就像你在图片中看到上面,我要显示一个警告每个用户输入在文本字段中禁止使用的值时签署。

我一直在阅读了很多Apple's documentation的,但我不明白,要实现哪些委托(NSTextFieldDelegateNSTextDelegate,或NSTextViewDelegate),还有,我不知道如何实现它在我AppDelegate.m文件和使用方法以及如何获取用户编辑的通知。

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

+0

我建议你为这些东西使用'NSNumberFormatter'。在界面构建器的边栏中甚至还有一个带有数字格式化程序的'NSTextField'。 – HAS

+1

感谢您的建议,但我已经有格式化程序正常工作,但我需要实施仅用于用户友好问题的视觉警告。 –

回答

5

我发现使用张贴在这个问题上的信息的解决方案... Listen to a value change of my text field

首先我要声明的N个STextFieldDelegate在AppDelegate.h文件

@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]; 
    } 
} 
1

使您的课程符合NSTextFieldDelegate协议。它需要成为该协议,因为在documentation中表示委托人符合的协议类型。

@interface MyClass的:NSObject的

而且实现委托的方法(只是把它们添加到你的代码)。例如

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

编辑:

我觉得你的情况可能会更好,以取代一个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 
} 
+0

你可以更具体一点关于我应该如何使用这个'textShouldBeginEditing'方法,因为这就是我正在尝试使用的方法,但我不知道如何使用。我在Cocoa Development方面仍然太新了(就像目前为止的2周)。 –

+0

我无法确切地告诉你该做什么,你想完成什么? – Merlevede

+0

我已经用解释我的想法的一些图片更新了我的问题。 –

相关问题