2012-06-13 39 views
1

我是UITextView的子类,我得到它的工作,但我也想在调用UITextView委托方法时做一些额外的工作。这是我到目前为止。自定义代表fo UITextView

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 

,这里是我的委托类

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; 
} 

它编译和运行没有错误。但委托函数从未被调用过。我错过了什么。

回答

3

当您初始化ThanaTextView时,委托尚未设置。

self.delegate = _thaanaDelegate; 

_thaanaDegate在这一点上是零。埃尔戈,你把它设置为零。

编辑:

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

所以我在哪里可以设置呢? –

+0

你可以在你的init方法之后(不是在你的方法中,但在调用它之前)设置它。或者使用像initWithDelegate这样的自定义init方法... – user1226119

+0

创建对象后,您必须对其进行设置。 @ user1226119在alloc之后但在init之前设置属性是一个非常糟糕的主意。 – CrimsonDiego