1

I've followed the instructions in this answer to create a reusable custom UIView laid out with a xib, which I can embed in my Storyboard by referencing the custom class. This works well and I can successfully load the view as advertised. However I want my embedding view controller(s) to be able to connect to IBActions of my embedded view. In the linked example, the custom view receives its own actions but this seems like poor design. I've worked around this by creating a delegate protocol that for custom view, which forwards events to its delegate, but this feels like more work than should be necessary. Additionally, Interface Builder will not allow me to wire up the delegate using references in the UI so I must instead do it programatically.

What I really want is to create a custom IB Action in my custom view, like someActionHappened, then wire that up in the embedding view controller. What is the best way to accomplish this?

Community
  • 1
  • 1
bloudermilk
  • 17,820
  • 15
  • 68
  • 98

1 Answers1

1
  • A .xib file has a File's Owner, which you can see and select when you're editing it.

  • When you load the nib, you get to specify the owner.

You can (and must) make the classes of these two things (the File's Owner in the nib and the actual owner at load time) match.

Thus, an action can be hooked from something in the nib to an IBAction in the File's Owner's class, and it will be fulfilled when the nib is loaded. Problem solved.

So:

However I want my embedding view controller(s) to be able to connect to IBActions of my embedded view

So the solution for you is to make your File's Owner (in your nib) and the actual owner (at nib-loading time) be your embedding view controller. Now your embedding view controller is allowed to have an IBAction and you can connect to it in the nib.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • If you want this to work with more than one class of view controller, you might have to do a little extra playing around with protocols or superclasses, but it can definitely be done. – matt Feb 21 '16 at 00:48