2012-07-11 82 views
1

我有一個關於初始化自定義委託的問題。 在MyScrollView initWithFrame方法中,我需要發送委託的第一個位置。但它仍然不爲人知,因爲我在初始化程序之後在MyCustomView中設置了委託。在init中設置併發送自定義委託方法?

我該如何解決這個問題,所以委託甚至在init內調用? 感謝您的幫助..

MyCustomView.m 

self.photoView = [[MyScrollView alloc] initWithFrame:frame withDictionary:mediaContentDict]; 
self.photoView.delegate = self; 
//.... 

MyScrollView.h 
@protocol MyScrollViewDelegate 
-(void) methodName:(NSString*)text; 
@end 
@interface MyScrollView : UIView{ 
//... 
    __unsafe_unretained id <MyScrollViewDelegate> delegate; 
} 
@property(unsafe_unretained) id <MyScrollViewDelegate> delegate; 


MyScrollView.m 

-(id) initWithFrame:(CGRect)frame withDictionary:(NSDictionary*)dictionary{ 
self.content = [[Content alloc] initWithDictionary:dictionary]; 

    self = [super initWithFrame:frame]; 
    if (self) { 
     //.... other stuff 

    // currently don´t get called 
    [self.delegate methodName:@"Test delegate"]; 
} 
return self; 
} 

回答

4

我相信你已經定義了:

- (id)initWithFrame:(CGRect)frame withDictionary:(NSDictionary *)dictionary;

然後,只需通過委託,太:

- (id)initWithFrame:(CGRect)frame withDictionary:(NSDictionary *)dictionary withDelegate:(id<MyScrollViewDelegate>)del;

在執行文件中:

- (id)initWithFrame:(CGRect)frame withDictionary:(NSDictionary *)dictionary withDelegate:(id<MyScrollViewDelegate>)del { 
    // your stuff... 

    self.delegate = del; 
    [self.delegate methodName:@"Test delegate"]; 

} 

使用它:

self.photoView = [[MyScrollView alloc] initWithFrame:frame withDictionary:mediaContentDict withDelegate:self]; 
+1

和Darren:非常感謝您爲您的快速回復。偉大的社區,夥計們。現在它運作完美。太好了!祝你今天愉快。 – geforce 2012-07-11 19:12:33

1

一種選擇可能是您的代理通過在你的自定義類的初始化:

-(id)initWithFrame:(CGRect)frame withDictionary:(NSDictionary*)dictionary delegate:(id)delegate 
{ 
    self = [super initWithFrame:frame]; 
    if (self == nil) 
    { 
     return nil; 
    } 
    self.content = [[Content alloc] initWithDictionary:dictionary]; 
    self.delegate = delegate; 
    //.... other stuff 

    // Delegate would exist now 
    [self.delegate methodName:@"Test delegate"]; 

    return self; 
} 
+1

與我的回答類似,只需要注意將方法簽名中的'delegate'變量名更改爲'delegate'以外的名稱,因爲使用了該名稱。 – Mazyod 2012-07-11 19:05:19