Search code examples
iphoneobjective-ciosuitextviewuitextviewdelegate

Custom Delegate fo UITextView


I am subclassing UITextView, and i got it working, but i also want to do some extra work when the UITextView Delegate methods are called. here is what i have so far.

ThanaaTextView.h

#import <UIKit/UIKit.h>

#import "ThaanaDelegate.h"


@interface ThaanaTextView : UITextView  {

    @private
    ThaanaDelegate * _thaanaDelegate;

}

ThanaaTextView.m

#import "ThaanaTextView.h"


@implementation ThaanaTextView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
       //do some extra stuff to textview
       //set delegate
       self.delegate = _thaanaDelegate;



    }
    return self;
}


}

@end

and here is my delegate class

ThaanaDelegate.h

 #import <UIKit/UIKit.h>
 #import <Foundation/Foundation.h>


@interface ThaanaDelegate : NSObject <UITextViewDelegate> {

    NSMutableArray* _lines;
}

   +(NSString*) reverseText:(NSString*) text withFont:(UIFont*) font carretPosition:(NSRange*) cpos Lines:(NSMutableArray*) lines Bounds:(CGRect) bounds;
-(void) setText:(NSString*) txt textview:(UITextView *)textView;


@end

ThaanaDelegate.m

 -(BOOL) textView:(UITextView*) textView shouldChangeTextInRange:(NSRange) range replacementText:(NSString*) text {
    //delegate method i want to do things in

    return NO;
}



-(void) setText:(NSString*) txt textview:(UITextView *)textView {

    //stuff
    return txt;
}

it compiles and runs without errors. but the delegate functions are never called. what am I'm missing.


Solution

  • When you init the ThanaTextView, the delegate is not yet set.

    self.delegate = _thaanaDelegate;
    

    _thaanaDelegate is nil at this point. Ergo, you are setting it to nil.

    Edit:

    ThaanaTextView *ttv = [[ThaanaTextView alloc] initWithFrame:textViewFrame];
    ttv.delegate = someDelegateHere;