2012-07-11 56 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