textDidChange未调用(NSTextFieldDelegate)

Mil*_*0R3 4 macos cocoa objective-c

步骤1.在xib中添加NSTextField

步骤2.在.h文件中添加NSTextFieldDelegate,将NSTextField控制拖动到文件的所有者以设置委托给它

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

- (void)textDidChange:(NSNotification *)notification{
    NSLog(@"textDidChange");
}
Run Code Online (Sandbox Code Playgroud)

但方法textDidChange:没有调用?

有什么不对吗?

rde*_*mar 13

文件的所有者不是应用程序委托 - 是您放置该方法的应用程序委托吗?您应该控制拖动到标记为app delegate的蓝色多维数据集.

编辑之后:委托收到的消息是controlTextDidChange:而不是textDidChange,所以实现那个.


Lea*_*ros 5

你需要注册一个观察者来听取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"];
}
Run Code Online (Sandbox Code Playgroud)

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

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

控件发布NSControlTextDidChangeNotification通知,如果控件的委托实现此方法,它会自动注册以接收通知

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