Create custom action in a class for use in Interfa

2019-08-12 09:30发布

问题:

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 ;-)

回答1:

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.