Ser Pounce Ser Pounce - 4 months ago 32
iOS Question

Multiple delegates per one object?

I have a

UIScrollView
that I need to subclass and within the subclass I need to attach the
UIScrollViewDelegate
so I can implement the
viewForZoomingInScrollView
method.

Then I have a
UIViewController
where I need to instantiate an object of this
UIScrollView
subclass that I created, and I would also like to make the UIViewController a
UIScrollViewDelegate
for this object so I can implement
scrollViewDidZoom
in this
UIViewController
class.

How is it possible to make one object have two delegates? (I know I could easily just have one delegate and just implement both methods there, but for design purposes I'd like to do it the way that I'm mentioning).

Answer

You don't want an object with 2 delegates. You want to keep your customScrollView keep the responsibility of its own UIScrollViewDelegate functions.

To make your parentVC respond to the delegate methods of UIScrollView as well you will have to make a custom delegate inside your customScrollView.

At the moment a UIScrollViewDelegate function gets called you will also call one of your delegate functions from your custom delegate. This way your parentVC will respond at the moment you want it to.

It will look somewhat like this.

CustomScrollView.h

@protocol CustomDelegate <NSObject>

//custom delegate methods
-(void)myCustomDelegateMethod;

@end

@interface CustomScrollView : UIScrollView <UIScrollViewDelegate>
{
    id<CustomDelegate> delegate
    //the rest of the stuff

CustomScrollView.m

-(void) viewForZoomingInScrollView
{
    [self.delegate myCustomDelegateMethod];
    //rest of viewForZoomingInScrollView code

ParentVC.h

@interface CustomScrollView : UIViewController <CustomDelegate>
{
    //stuff

ParentVC.m

-(void)makeCustomScrollView
{
     CustomScrollView *csv = [[CustomScrollView alloc] init];
     csv.delegate = self;
     //other stuff

}

-(void)myCustomDelegateMethod
{
   //respond to viewForZoomingInScrollView
}

I hope this fully covers your problem. Good luck.