【问题标题】:tableView:cellForRowAtIndexPath: never being calledtableView:cellForRowAtIndexPath: 永远不会被调用
【发布时间】:2012-08-20 17:43:10
【问题描述】:

我有一个UITableView,在UIView 中名为tblParentComments,属于CBox

我确实将我的视图设置为我的表视图的数据源和委托,并且我的视图确实实现了这些协议tableView:numberOfRowsInSection: 方法确实被调用 并返回一个非零值。但是函数tableView:cellForRowAtIndexPath:从未被调用过。

我注意到,如果我将方法 tableView:cellForRowAtIndexPath: 放入 cmets 中,Xcode 不会停止编译并出现“需要tableView:cellForRowAtIndexPath:”之类的错误——应用程序只是运行并显示一个空表。

我不明白。有任何想法吗?这是我的观点的代码:

接口 CBox.h

@interface CBox : UIView <UITableViewDelegate, UITableViewDataSource> 

并且在实现文件中:

- (id) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {        
        tblParentComments = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.frame.size.width, frame.size.height)];
        tblParentComments.delegate = self;
        tblParentComments.dataSource = self;
        //tblParentComments.userInteractionEnabled = NO;
        tblParentComments.backgroundColor = [UIColor clearColor];
        tblParentComments.separatorStyle = UITableViewCellSeparatorStyleNone;
        tblParentComments.bounces = NO;
        [self addSubview:tblParentComments];
    }
    return self;
}

#pragma mark - UITableViewDelegate + UITableViewDatasource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"num of rows = %d", parentComents.count);
    return 1;  // I set a non-zero value for test
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 .... // I set a breakpoint here, never been called here
}

【问题讨论】:

  • 感谢您的快速回复!我修改了原帖。
  • 这个视图是在 xib 中创建的,还是通过代码创建的? delegatedatasource 连接在哪里?在界面生成器中?
  • @W'rkncacnter:它是在代码中创建的,参见“initWithFrame”。 tblParentComments.delegate = 自我; tblParentComments.dataSource = self;
  • 但是视图本身是在哪里创建的?
  • 在 viewController 中,我创建了这个视图并将其添加到 self.view 中,在重新加载数据后,我调用了“[tblParentComments reloadData];”,

标签: objective-c cocoa-touch uitableview


【解决方案1】:

是的..我有同样的问题...我刚刚找到了解决方案。

在我的课堂上,我使用不同的 inits 和不同的参数。

在我的-(void)viewDidLoad 中,我使用alloc 使用CGRectZero 的表格视图,并且仅在这种情况下,如果您不设置 UITableView 的 FRAME,则:

  • numberOfRowsInSection 将被调用

  • cellForRowAtIndexPath 永远不会被调用

我刚刚设置了我的 UITableView 框架,它的工作原理。

【讨论】:

    【解决方案2】:

    当我阅读上面的 cmets 时,我可以弄清楚几件事:

    您可能弄乱了代码的一些结构。您应该始终遵守视图控制器中的协议 - !不查看。或者,我喜欢做的事情(因为它让我可以更好地控制我的代码并保持事情干净),将协议从视图控制器中分离出来 - 意味着创建新对象(模型对象),它将处理表所需的所有内容并且它将符合表委托和数据源。

    如果您明智地组织代码,则应避免上述情况。

    另外,我相信您可能有 2 个符合表协议的对象,这就是事情变得丑陋的地方。

    【讨论】:

      猜你喜欢
      • 2012-10-27
      • 2013-10-12
      • 2012-03-27
      • 2013-08-29
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 2015-10-15
      相关资源
      最近更新 更多