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

后端 未结 2 1123
不思量自难忘°
不思量自难忘° 2020-12-03 16:09

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

相关标签:
2条回答
  • 2020-12-03 16:48

    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 <Appkit/Appkit.h>
    @class MouseDownTextField;
    
    @protocol MouseDownTextFieldDelegate <NSTextFieldDelegate>
    -(void) mouseDownTextFieldClicked:(MouseDownTextField *)textField;
    @end
    
    @interface MouseDownTextField: NSTextField {
    }
    @property(assign) id<MouseDownTextFieldDelegate> delegate;
    @end
    
    MouseDownTextField.m:
    #import "MouseDownTextField.h"
    
    @implementation MouseDownTextField
    -(void)mouseDown:(NSEvent *)event {
      [self.delegate mouseDownTextFieldClicked:self];
    }
    
    -(void)setDelegate:(id<MouseDownTextFieldDelegate>)delegate {
      [super setDelegate:delegate];
    }
    
    -(id)delegate {
      return [super delegate];
    }
    
    AppDelegate.h:
    @interface AppDelegate <MouseDownTextFieldDelegate>
    ...
    @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.

    0 讨论(0)
  • 2020-12-03 16:57

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

    0 讨论(0)
提交回复
热议问题