22

How do I attach a event to a NSTextField for when I click on it? Are there any examples out there?

AdamB
  • 3,101
  • 4
  • 34
  • 44
  • When the user clicks on the text field or when the user enters the text field (e.g. by clicking inside it or typing Tab)? –  Apr 08 '11 at 09:41
  • 1
    When the user clicks on the text field. – AdamB Apr 08 '11 at 18:14
  • Take a look at http://stackoverflow.com/questions/684166/which-delegate-method-i-should-use-to-respond-to-clicks-on-a-nstextfield – Ryan Jan 01 '12 at 07:36
  • have you get any solution , i am also finding an idea to do it??? – Neelam Verma Sep 04 '14 at 03:58

3 Answers3

16
NSClickGestureRecognizer *click = [[NSClickGestureRecognizer alloc] initWithTarget:self action:@selector(myTextFieldClicked:)];
[self.myTextField addGestureRecognizer:click];
John Erck
  • 9,478
  • 8
  • 61
  • 71
7

You can try this: It works for me.

    @interface customTextField : NSTextField
    @property (strong) id target;
    @end

    @implementation customTextField

    - (void)mouseDown:(NSEvent *)theEvent
    {
        [self sendAction:@selector(clickAction:) to:[self target]];
    }

    @end

Thanks.

Neelam Verma
  • 3,232
  • 1
  • 22
  • 33
  • It is better to use target's action. You can set it by CTRL+Drag to source code the action. [self sendAction:self.action to:self.target]; – Borzh Sep 21 '15 at 01:53
  • 2
    You should not copy others answer. Its original source is : http://stackoverflow.com/questions/9184555/click-on-nstextfield-label-to-emulate-hyperlink-to-a-folder – Anoop Vaidya Dec 23 '15 at 09:10
  • I did not copy , Its coincidence that the link also has given same answer. – Neelam Verma Apr 08 '16 at 13:24
  • 1
    Anoop Vaidya and Verma: http://www.cocoabuilder.com/archive/cocoa/222029-how-can-use-nstextfield-like-button.html#222519 – Mike97 Sep 26 '16 at 20:35
-4

The method you are looking for is - textShouldBeginEditing:

You have to set the delegate of the NSTextField, first of all.

saimonx
  • 516
  • 1
  • 8
  • 25
  • 1
    Are there any examples I could look at? – AdamB Apr 08 '11 at 00:12
  • 27
    `–control:textShouldBeginEditing:` isn’t sent when the user clicks the text field. It is sent when the user starts typing text in the text field. –  Apr 08 '11 at 09:51