2012-06-13 42 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