表视图返回有趣的错误

The*_*Man -4 iphone xcode cocoa-touch objective-c ios

好的我正在使用目标c创建表视图,但数据源无法正常工作...

我的错误:

2012-06-02 20:14:39.891 Dot Golf Scoring[195:707] *** Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit/UIKit-1914.85/UITableView.m:6061
2012-06-02 20:14:39.895 Dot Golf Scoring[195:707] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
Run Code Online (Sandbox Code Playgroud)

我的代码:

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 16;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @"Comments On Your Round";
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

    cell.textLabel.text = @"Text Label";

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

为什么表视图没有填满这个假数据???

MCK*_*pur 7

你永远不会初始化细胞.使用此代码:

    - (UITableViewCell *)tableView:(UITableView *)tableView2 cellForRowAtIndexPath:(NSIndexPath *)indexPath 

{


    UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:@"UITableViewCell"];


    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:@"UITableViewCell"]
                autorelease];


        cell.textLabel.text = nil;                


    }

    if (cell) {

        //customization 
        cell.textLabel.text = @"Text Label";
    }

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

你说你是一个菜鸟....让我解释一下尝试拿起这本书:

大书呆子牧场指南

您的想法是,出列的基本上是正确的吗?没有!出列基本上是任何不可见的单元格,也就是你滚过它.因此,cell == nil可能会在四种情况下调用(我能想到):

  1. 当我们第一次设置表视图时(单元格将为零)
  2. 当我们重新加载数据时
  3. 每当我们到达这个班级
  4. 当单元格从表格视图中变得不可见时

因此,出列的标识符就像一个ID.然后在看看,如果声明cellnil,我们初始化cell,您可以看到被覆盖的init方法:initWithStyle.这只是什么类型cell,有不同的类型,您可以自定义不同的变量.我给你看了默认值.然后我们使用reuseIdentifier前面提到的出列标识符.他们必须匹配!我textLabel只是为了更好的结构,在这种情况下,每个单元格都有相同的文本,所以它并不重要.它使得出列的单元格能够通过您实现的正确定制而返回.一旦单元格实际有效,我们就可以自定义.

此外,您为每个单元格使用相同的文本.如果您确实希望每个单元格都有不同的文本,请熟悉NSArray.然后,你可以提供的阵列countnumberOfRowsForSection,然后做这样的事情:

cell.textLabel.text = [array objectAtIndex: [indexPath row]];
Run Code Online (Sandbox Code Playgroud)

方法中提供indexPathNSIndexPath参数在哪里cellForRowAtIndexPath.该row变量是row数字,所以一切都适合!

哇,这是很多东西!现在停止成为一个客观的菜鸟并开始阅读一些书!

欲了解更多信息:

表格查看Apple文档