2012-07-27 66 views
4

步骤1.添加的NSTextField在厦门国际银行textDidChange不叫(NSTextFieldDelegate)

第2步:添加NSTextFieldDelegate在.h文件中,按住Control键拖动的NSTextField以文件的所有者委托设置为它

第3步,在.m文件中添加方法:

- (void)textDidChange:(NSNotification *)notification{ 
    NSLog(@"textDidChange"); 
} 

但是方法textDidChange:未调用?

有什么错误吗?

回答

13

该文件的所有者不是应用程序委托 - 是您将该方法放在哪里的应用程序委托?您应该控制拖动到标有“应用程序委托”的蓝色立方体。

编辑后:代理收到的消息是controlTextDidChange:不是textDidChange,所以实现该代替。

+0

的厦门国际银行与windowController创建,没有应用程序委托。 – Mil0R3 2012-07-27 03:12:33

+0

@Veelian,看到我编辑的答案 – rdelmar 2012-07-27 03:48:22

+0

谢谢,它的工作原理,我仍然拼图:我发现textDidChange:在NSTextFieldDelegate它不起作用,但controlTextDidChange:不在NSTextFieldDelegate。 – Mil0R3 2012-07-27 04:06:42

4

您需要注册一个观察者才能收听NSNotification

// When the NSWindow is displayed, register the observer. 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(controlTextDidChange:) name:NSControlTextDidChangeNotification object:nil]; 

- (void)controlTextDidChange:(NSNotification *)obj { 
    // You can get the NSTextField, which is calling the method, through the userInfo dictionary. 
    NSTextField *textField = [[obj userInfo] valueForKey:@"NSFieldEditor"]; 
} 

看来,通过NSFieldEditor返回的对象是一个NSTextView,而不是同NSTextField对象,你可能期望。

但是,根据苹果文档,如果您实现此方法并且控件委托已注册到此对象,则通知应自动注册。

控制职位NSControlTextDidChangeNotification通知,如果控制的委托实现这个方法,它会自动注册接收通知

来源:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSControl_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/controlTextDidChange

+0

访问'[textField stringValue]'时,我确实崩溃了,我已经成功地使用了'NSText *'类类型而不是NSTextField – nio 2014-07-04 09:10:03