在我的 Storyboard中,我有一个简单的 View Controller ,其中包含一个 UITableView。
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/