Which delegate method should I use to respond to clicks on an NSTextField?

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

I am trying to respond to a click within a textfield. When the click occurs, I am going to open a panel. My initial thought was to use a delegate method to respond to the click event - but I found that:

This method doesn't work:

(void)textDidBeginEditing:(NSNotification *)aNotification 

This method does work, but only when I actually edit the text within the text field, not when I first click it. And - if I edit the text a second time, this method stops working:

(void)controlTextDidBeginEditing:(NSNotification *)aNotification 

I could use as much detail as possible - or a code example, ideally. I know that an nstextfield inherits from NSControl, which has a mouseDown event. Is there a similar way to respond to the event with a textfield, also?

回答1:

Since NSTextField inherits from the NSControl class, it also inherits the -(void)mouseDown:(NSEvent*) theEvent method.



回答2:

I needed to have an NSTextField call a delegate function upon clicking it today, and thought this basic code might be useful. Note that NSTextField already has a delegate and that in SDK v10.6, the delegate already has a protocol associated with it. Note that if you don't care about protocols, compiler warnings, etc., you don't need the protocol and property declarations or the getter and setter.

MouseDownTextField.h:  #import  @class MouseDownTextField;  @protocol MouseDownTextFieldDelegate  -(void) mouseDownTextFieldClicked:(MouseDownTextField *)textField; @end  @interface MouseDownTextField: NSTextField { } @property(assign) id delegate; @end  MouseDownTextField.m: #import "MouseDownTextField.h"  @implementation MouseDownTextField -(void)mouseDown:(NSEvent *)event {   [self.delegate mouseDownTextFieldClicked:self]; }  -(void)setDelegate:(id)delegate {   [super setDelegate:delegate]; }  -(id)delegate {   return [super delegate]; }  AppDelegate.h: @interface AppDelegate  ... @property IBOutlet MouseDownTextField *textField; ...  AppDelegate.m: ...   self.textField.delegate = self; ... -(void)mouseDownTextFieldClicked:(MouseDownTextField *)textField {   NSLog(@"Clicked");   ... } ... 

If you're building with 10.5 SDK, don't have the protocol inherit from NSTextFieldDelegate.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!