我做了一个自定义 View 。
我设置了两种启动方式,
1. initWithFrame(用于代码初始化)
2. initWithCoder(用于 Storyboard初始化)
在我的自定义类中
- (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;
}
然后,我将 View 添加到 Storyboard并在身份检查器中更改类。 我将 View 连接到 viewcontroller 属性。
我设置委托(delegate)和数据源
在我的 View Controller 中
@interface ViewController () <UIControlViewDataSource, UIControlViewDelegate>
@property (weak, nonatomic) IBOutlet UIControlView *controlView;
@end
- (void)viewDidLoad
{
self.controlView.delegate = self;
self.controlView.dataSource = self;
}
initWithCoder 在 viewDidLoad 之前运行,
正因为如此,委托(delegate)永远不会运行,因为在我在 View Controller 的 viewDidLoad 中设置委托(delegate)之前,自定义类中的 initWithCoder 正在运行。
委托(delegate)属性将具有 NULL 值。
如何设置委托(delegate)?
最佳答案
如果您从 xib 或 Storyboard 实例化这些对象(看起来您基于 IBOutlet
),则应该在 -(void)awakeFromNib
中设置您的委托(delegate)>
此时所有的网点都已经设置好了。
您不必依赖对象的实例化顺序。你应该让它们都被实例化,设置导出,然后做任何你需要用你的委托(delegate)做的事情
关于ios - 为自定义类设置委托(delegate)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25534797/