objective-cswiftbindingnsbuttonnscollectionviewitem

NSButton binding to NSCollectionViewItem: representedObject?


When I pre-added a button to the NSCollectionViewItem's view, I can bind its action in the inspector:

enter image description here

Which works without problem.

Now I'd like to create that button programmatically within the view's mouseDown:, what should I assign to the bind: option for the same result as the "Bind to: Collection View Item" in inspector?

Here's the code: (Swift)

aButton!.bind(
    "argument",
    toObject: ???, // <- what should I set here?
    withKeyPath: "representedObject",
    options: options
)

EDIT: I was able to do it by subclassing NSCollectionView then override newItemForRepresentedObject: to assign the representedObject to the subclass view.

Still like to know if there are ways without subclassing NSCollectionView.


Solution

  • You should bind to the NSCollectionViewItem instance which owns the view of which the button is a descendant.

    From what context are you creating the button and trying to bind it? Is this in a controller of the collection view? Or is it in the collection view item itself (which is a controller of the collection view item view)? Or perhaps it's in custom view class, although that would be a bit strange.

    From the controller of the collection view, you can use -itemAtIndex: to get the relevant collection view item.

    From the collection view item, you would just use self. However, in this case bindings don't really get you much. You might as well just set the button's target and action and do something with the representedObject in the action method.

    If you're doing this from a view, then you need a way to obtain a reference to the collection view item. You should add a weak outlet on the view that you connect to the collection view item in the NIB. Then, you would use that outlet to get the collection view item for that bind() call.