1

我有一个关于初始化自定义委托的问题。在 MyScrollView initWithFrame 方法中,有我需要发送我的委托的第一个位置。但是那里仍然未知,因为我在初始化程序之后在 MyCustomView 中设置了委托。

我该如何解决这个问题,所以即使在 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

2 回答 2

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];
于 2012-07-11T19:00:24.283 回答
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;
}
于 2012-07-11T19:01:36.130 回答