Skip to content

Instantly share code, notes, and snippets.

@boundsj
Created June 9, 2014 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boundsj/b0d1568ddff863bb9d90 to your computer and use it in GitHub Desktop.
Save boundsj/b0d1568ddff863bb9d90 to your computer and use it in GitHub Desktop.
Subclass with Internal Delegate and Message Forwarding
#import <UIKit/UIKit.h>
@interface MyTextView : UITextView
@end
#import "MyTextView.h"
// UITextViewDelegate impl for internal use only by MyTextView
@interface MyTextViewInternalDelegate : NSObject <UITextViewDelegate>
@property (weak, nonatomic) id<UITextViewDelegate> userDelegate;
@end
@interface MyTextView ()
@property (strong, nonatomic) MyTextViewInternalDelegate *internalDelegate;
@end
@implementation MyTextView
- (id)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
self.internalDelegate = [[MyTextViewInternalDelegate alloc] init];
[super setDelegate:self.internalDelegate];
}
return self;
}
#pragma mark UITextViewDelegate custom work
- (void)didBeginEditing {
NSLog(@"================> whatever MyTextView needs to do internall as a delegate");
}
#pragma mark Overrides
- (void)setDelegate:(id<UITextViewDelegate>)delegate {
self.internalDelegate.userDelegate = delegate;
}
- (id<UITextViewDelegate>)delegate {
return self.internalDelegate.userDelegate;
}
@end
@implementation MyTextViewInternalDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
[(MyTextView *)textView didBeginEditing];
if ([self.userDelegate respondsToSelector:_cmd]) {
[self.userDelegate textViewDidBeginEditing:textView];
}
}
#pragma mark Message Forwarding
- (BOOL)respondsToSelector:(SEL)selector {
return [self.userDelegate respondsToSelector:selector] || [super respondsToSelector:selector];
}
- (void)forwardInvocation:(NSInvocation *)invocation {
[invocation invokeWithTarget:self.userDelegate];
}
@end
#import <UIKit/UIKit.h>
@class MyTextView;
@interface TestViewController : UIViewController
@end
#import "TestViewController.h"
#import "MyTextView.h"
@interface TestViewController () <UITextViewDelegate>
@property (weak, nonatomic) IBOutlet MyTextView *myTextView;
@end
@implementation TestViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.myTextView.delegate = self;
}
#pragma mark <UITextViewDelegate>
- (void)textViewDidBeginEditing:(UITextView *)textView {
NSLog(@"================> user delegate gets to do stuff too");
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment