Create custom action in a class for use in Interface Builder

571 Views Asked by At

I want to create a custom action connection in a class, which should be visible in Interface Builder. For example - I add action / target properties to NSView class just like this:

weak open var object: AnyObject?    
open var something: Selector?

The action is something and the target is object. Now I want in Interface Builder to have 'Send Action' link / connection available for something and to be able to make connection to a @IBAction method to some class (for example the controller of the view), just like it can be done for a simple NSButton. Maybe this is not possible, or maybe I must add some keywords in front of the custom action / target pair, the same way we need to make a property @IBInspectable to appear in Attributes Inspector.

Any help is welcome ;-)

2

There are 2 best solutions below

7
Duncan C On

I don't think you can do that. You can add @IBInspectable properties to custom NSView subclasses, but there is no selector or action data type for properties. The only allowed types are Boolean, Number, String, Localized String, Point, Size, Rect, Range, Color, Image, Nil.

Interface Builder has hard-wired support for handling the target-action properties of controls.

(BTW you should probably add the Mac OS tag to your quesiton. Most Apple traffic on this board is iOS-related.

EDIT:

As somebody said in a comment, if you're creating an object that has a target/action, it should probably be an NSControl, not an NSView. Controls are the object family that handle target-actions, and there IS a mechanism in Interface Builder for adding target/actions to controls.

0
Carl Lindberg On

In iOS, there is one somewhat cheesy option -- you could have an outlet to a UIBarButtonItem, and someone could then drop a standalone UIBarButtonItem in their xib or storyboard. The UIBarButtonItem can then have the target/action, and your class could then pull the target/action from there in awakeFromNib and assign the values to your own class. That approach may be replicable in MacOS using NSToolbarItem, but I have not tried. It's a kludgy option really, as it requires extra xib objects and may not be too obvious what is going on, but it can work. Basically, the UIBarButtonItem / NSToolbarItem would only be acting as a container for the target/action values.

If you can't subclass NSControl, it would seem the preferred option is to have a delegate, probably. That is usually fine, unless one controller needs to be the delegate for multiple instances of your class, in which case the delegate methods get more tedious. Another option is to have your class have a block property, which is performed upon the action, but blocks must be assigned in code and not set up in Interface Builder.