【发布时间】:2014-08-27 18:44:38
【问题描述】:
我制作了一个自定义视图。
我设置了两种启动方式,
1.initWithFrame(用于代码初始化)
2. initWithCoder(用于情节提要初始化)
在我的自定义类中
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// [self setUp] method contain the code to run the delegate.
[self setUp];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// [self setUp] method contain the code to run the delegate.
[self setUp];
self.backgroundColor = [UIColor greenColor];
}
return self;
}
然后,我将视图添加到情节提要并更改身份检查器的类。 我将视图连接到 viewcontroller 属性。
我设置了委托和数据源
在我的视图控制器中
@interface ViewController () <UIControlViewDataSource, UIControlViewDelegate>
@property (weak, nonatomic) IBOutlet UIControlView *controlView;
@end
- (void)viewDidLoad
{
self.controlView.delegate = self;
self.controlView.dataSource = self;
}
initWithCoder 在 viewDidLoad 之前运行,
因此,委托将永远不会运行,因为在我在视图控制器的 viewDidLoad 中设置委托之前,我的自定义类中的 initWithCoder 正在运行。
并且委托属性将具有 NULL 值。
如何设置委托?
【问题讨论】:
-
你为什么认为,在设置委托之前不应该调用 initWithCoder ?
-
@pawan initWithCoder 运行 [self setUp] 方法,其中包含从委托方法中汇集数据的代码,如果委托尚未设置,则该方法无法运行
标签: ios objective-c storyboard