implementing Target - Action pattern in custom view

1k views Asked by At

I've created a custom view which inherits from NSView. My goal is to notify my NSWindowControl which is associated with the window that contains the custom view, when the user click the the custom view.

I would like to implement this using the Action - Target pattern , just like a NSButton does. So that I will be able connect the custom view with an action in the window controller using the Interface Builder.

1

There are 1 answers

4
trojanfoe On

Add the following to your custom view header file:

@interface MyCustomView : NSView

@property (weak, nonatomic) id userClickedTarget;
@property (assign, nonatomic) SEL userClickedAction;

@end

Synthesize the getter/setter in the custom view implementation file (this is actually optional with recent versions of Xcode/clang):

@synthesize userClickedTarget = _userClickedTarget;
@synthesize userClickedAction = _userClickedAction;

and to call the target/action within your code:

if (_userClickedTarget && _userClickedAction) {
    [_userClickedTarget performSelector:_userClickedAction
                             withObject:self
                             afterDelay:0.0];
}

Note that using performSelector:withObject:afterDelay decouples the call from your view code and makes it run the next time the runloop is processed.