ios - 在 UITableView 子类中设置 UITableViewDataSource 无效

标签 ios objective-c uitableview datasource

在我的 Storyboard中,我有一个简单的 View Controller ,其中包含一个 UITableView。

enter image description here

SceneFormVC.m

@property (nonatomic, strong) IBOutlet SceneFormTV  *sceneFormTable;

在改进我的 MVC 和制作“更轻便”的 VC 的过程中,我将 UITableView 子类化以更好地分离关注点和代码重用。

SceneFormTV.h

@interface SceneFormTV : UITableView <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

SceneFormTV.m

@implementation SceneFormTV

- (id)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self)
    {
         self.dataSource = self;
         self.delegate   = self;
    }

    return self;
}

这里的问题是,当我在 initWithCoder 期间尝试在我的子类中设置 dataSource/delegate = self(由 Storyboard设置调用)时,它没有导致其余的 UITableView 方法被调用的效果

但是如果我在主 VC (SceneFormVC.m) 中设置 dataSource/delegate 指针,那么 UITableView 会按预期工作。

@implementation SceneFormVC

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.sceneFormTable.dataSource = self.sceneFormTable;
    self.sceneFormTable.delegate   = self.sceneFormTable;

我不太明白为什么我的 SceneFormTV 子类在内部使用完全相同的 dataSource/delegate 指针设置自身时无法运行?

最佳答案

这个最初是针对 IBOutlets 的,但在您的情况下也应该有效。

The objects do not yet exist when initWithCoder is called, and they do when viewDidLoad is called. Check your initWithCoder method by logging out the value of worldView using something like:

NSLog(@"%@", self.datasource);

and it will be nil. They will be initialized before the call to viewDidLoad, so you can set a them there.

来源:Objective-C iOS Development Using viewDidLoad or initWithCoder when setting Variables and Why?

关于ios - 在 UITableView 子类中设置 UITableViewDataSource 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25029300/

相关文章:

iphone - 在 UITableView 中使用 UITableViewCell

ios - 垂直滚动背景-Sprite Kit

iphone - 我的 Default.png 使用什么样的图像?我正在使用 iPhone 5's native resolution WITH the status bar, but it won' t 工作

ios - 数据未从 iphone 传输到真实设备上的 iWatch (AppleWatch)

ios - Mapbox Annotation 图像居中

objective-c - macOS:检测所有应用程序启动,包括后台应用程序?

ios - UITableView 单元格重叠

ios - 禁止在 Swift 中自动旋转一个组件?

iphone - 在 UIView 中嵌入实时摄像头 View

ios - 如何在我输入 UITextField 时获取谷歌建议并将其放在 UITableView 上