Step 1. Add a NSTextField in xib
Step 2. Add NSTextFieldDelegate in .h file,Control-drag NSTextField to File's Owner to set delegate to it
Step 3, In .m file add the method:
- (void)textDidChange:(NSNotification *)notification{
NSLog(@"textDidChange");
}
but the method textDidChange: not called?
Is any mistake?
The file's owner isn't the app delegate -- is the app delegate where you put that method? You should control drag to the blue cube labeled app delegate.
After Edit: The message that the delegate receives is controlTextDidChange: not textDidChange, so implement that one instead.
You need to register an observer to listen for the 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"];
}
It seems, the object returned by NSFieldEditor
is a NSTextView
, instead of the same NSTextField
object, which you may expect.
However, according to Apples documentation, if you implement this method and the controls delegate is registered to this object, the notification shall be automatically registered.
The control posts a NSControlTextDidChangeNotification notification, and if the control’s delegate implements this method, it is automatically registered to receive the notification
Source: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSControl_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/controlTextDidChange:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With