1

I'm having a hard time getting my head around custom delegation - I would be most grateful if someone could help me:

I have a UIViewController with a tab bar controller, and each of these contains a subclassed UIView. In one of the views, I have a UIButton in which I want to load a UIDocumentInteractionController. I already have the code to do this second part, as the document controller needs access to a UIViewController in order to get pushed to the stack.

But how can my UIView get access to the UIViewController?

I've read a plethora of things on SO tonight, such as:

  • It can't be done
  • Set the UIViewController as a property of the UIView so it knows which it belongs to
  • Calling nextResponder on the UIViewController
  • Delegation

I can happily hit my -(void)buttonPressed: (id)sender method, but where should it go from here to implement delegation? Should it just fire something like [delegate documentRequested: sender] assuming this method exists in my view controller?

Thanks in advance for any assistance.

Luke
  • 11,426
  • 43
  • 60
  • 69

1 Answers1

2

I recently posted a detailed answer on how to use custom delegation. You can check it out here: dismissModalViewController AND pass data back

What you want to do here is implement the protocol in your UIView and set the UIViewController to be it's delegate.

To help you understand the linked answer better, in the answer, secondviewcontroller is equivalent to your UIView and firstviewcontroller is equivalent to your UIViewController.

Community
  • 1
  • 1
Sid
  • 9,508
  • 5
  • 39
  • 60
  • Fantastic, thank you so much for this. I've got it working and it's perfect. I think the areas I missed out from the code in your linked answer was an indifference in setting the delegate as a property and the respondsToSelector call. In your example, the user was able to pass one string in the delegate's method. Is 1 item the limit that I can send back to my UIViewController? – Luke Jun 02 '11 at 09:14
  • Nope! That's the beauty of it.... you can pass as many arguments (object references, primitives, etc.... like a normal method) :) – Sid Jun 02 '11 at 14:20
  • 1
    For multiple arguments, the respondstoselector if check will look a little different. I've edited that answer since this is something I should have mentioned anyway so you can check it out... :) – Sid Jun 02 '11 at 14:26
  • Oh and needless to say; Bear in mind to manage your memory well when you're passing object references back and forth. Peace... – Sid Jun 02 '11 at 14:28
  • Yep, will do. I was passing through my subclassed UIView, but in my situation I am only looking to pass through a couple of strings. I was certain you could pass in multiple arguments/objects - just wasn't entirely sure where to edit the delegate calls. Thanks again for your help, it's really nice to see the code working :) – Luke Jun 02 '11 at 15:32