ios - 为自定义类设置委托(delegate)对象

标签 ios objective-c storyboard

我做了一个自定义 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 在 vi​​ewDidLoad 之前运行,

正因为如此,委托(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/

相关文章:

ios - 为什么我们不需要为局部变量提供初始值?

ios - 向 AppDelegate 发送消息不适用于应用内购买

xcode - UIViewController _loadViewFromNibNamed :bundle loaded the "XXXViewController" nib but the view outlet was not set. ' -*使用 Storyboard*

ios - Swift 3 CoreData 在 iOS 9 设备上崩溃

ios - UICollectionView.dequeueReusableCell 崩溃

ios - 将相机应用程序旋转复制到风景 IOS 6 iPhone

ios - 在 NavigationController 中跳过登录 View Controller

objective-c - NSString cStringUsingEncoding 返回值的生命周期

iOS 5 自定义标签栏取消分配 TableView ?

iOS Storyboard 切换到一个在 AppDelegate 上没有 segue 的 View