7

I have an NSTextField label and I want something to happen when a user clicks on it.

I thought I could create an IBAction and link this to the label but nothing seems to happen.

Any suggestions?

Intentions:

The reason why I am doing this is because I want a label that is a hyperlink to a folder. Perhaps I am taking the wrong approach altogether?

IBAction definition in my PersonController.m

- (IBAction)surnameLabelSelected:(id)sender {
    NSLog(@"This should do something!");
}

XIB File

In the XIB file I have made a Received Actions connection between surnameLabelSelected and the StaticText NSTextField label.

Coderama
  • 11,050
  • 12
  • 44
  • 58

3 Answers3

22

You've got a couple options. Francis's answer is one option. Another option is to subclass NSTextField and override -mouseDown:. Something like this (written off the top of my head, not tested):

@interface ClickableTextField : NSTextField
@end

@implementation ClickableTextField

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

@end

If NSTextField is closer in style to the appearance you need, this might be the better approach. If you need NSButton's features (highlight upon click, etc) go with Francis's solution.

Andrew Madsen
  • 21,309
  • 5
  • 56
  • 97
12

Labels are non-editable text fields thus don't send actions to their targets. You want to use an NSButton and turn off its border-drawing and size it to fit its text as best as possible to simulate a label.

Francis McGrew
  • 7,264
  • 1
  • 33
  • 30
  • Good suggestion! Ultimately, I am trying to create a hyperlink field and thought I could modify the label's style to look like a hyperlink. Is your suggestion still the right course of action? – Coderama Feb 08 '12 at 01:29
  • 1
    Unfortunately creating a realistic hyperlink in a text field is a bit more involved than setting a link attribute. I recommend you check out [DSClickableURLTextField](http://www.nightproductions.net/developer.htm#DSClickableURLTextField) for reference. – Francis McGrew Feb 08 '12 at 05:12
  • 2
    This doesn't quite work today. NSButtons love to draw their own background and change their colors depending on their type. There isn't a built in button type and combination of options to eliminate this anymore. – Sean256 Jun 26 '16 at 22:50
3

Another option is to create a transparent button (without title/image/border, momentary push in) in front of the label, with the same frame as label's. And set button's action accordingly.

Borzh
  • 5,069
  • 2
  • 48
  • 64