0

I have a textView "TexV" which have a custom class "TexV_Class" inherited from UITextView and I have a viewController "VC" with custom class named "VC_Class"

Now how can I make both classes "TexV_Class" and "VC_Class" delegate and make them work together? Is it even possible that same delegate method (eg. textViewDidChange) in BOTH classes runs (leaving the sequence of running for now)

I although had made both classes delegate but only one runs (that of VC_Class having textView delegate methods run)

djay
  • 375
  • 2
  • 18
  • If you really need this (you might want to reconsider you app structure first) take a look at [MultiDelegate](https://cocoapods.org/pods/MultiDelegate) or [ILABMultiDelegate](https://cocoapods.org/pods/ILABMultiDelegate). There are some gotchas using these classes but are well documented. – Rok Jarc Jul 04 '16 at 09:01

2 Answers2

1

You can't. The delegate mechanism works by having a single callback object, if you want more than one item to react based on the delegate you can go around this in one of two ways:

1- Fire a notification on one of your delegate so that the other delegate can act accordingly

2- set a custom delegate on TexV_Class that conforms to the method of UITextView that the VC_Class wants to adopt, and have TexV_Class call this delegate from it's delegate callback.

Danny Bravo
  • 4,534
  • 1
  • 25
  • 43
0

I suggest you 3 ways to do this:

1) Use NSNotificationCenter (the pattern help 1 object communicate one-to-many objects)

2) Use multicast delegate pattern. Implementation detail, you can refer this http://blog.scottlogic.com/2012/11/19/a-multicast-delegate-pattern-for-ios-controls.html

3) Use Proxy Design pattern. (This way I choosen)

class MyTextView.h

@protocol NJCustomTextViewDelegate <NSObject>

- textViewShouldBeginEditing:
- textViewDidBeginEditing:
- textViewShouldEndEditing:
- textViewDidEndEditing:

@end

@property (nonatomic, weak) id< NJCustomTextViewDelegate >textViewDelegate;

Use this:

in MyTextView.m

self.delegate = self;

-  (void)textViewShouldBeginEditing:(UITextView)textView
{
    // Handle business logi
    // .... Do your logic here

    if ([self.textViewDelegate responseToSelector:@selector(textViewShouldBeginEditing:)])
    {
        [self.textViewDelegate textViewShouldBeginEditing:self];
    }
}

In MyViewController.m

MyTextView textView = ....
textView.textViewDelegate = self;
Proton
  • 1,335
  • 1
  • 10
  • 16