【问题标题】:Returning UITableViewCell custom cell返回 UITableViewCell 自定义单元格
【发布时间】:2016-06-13 22:02:14
【问题描述】:

我有一个 UITableViewCell 的子类,称为 ReminderCell

ReminderCell 有一个我写的叫做backToPlaceAnimation 的方法。

问题是,例如,如果我想在第一个 ReminderCell 上使用 RemindersVC 调用 backToPlaceAnimation 并使用 tableView: cellForRowAtIndexPath: 它没有返回正确的对象(它是 UITableViewCell 对象而不是 ReminderCell) .

我怎样才能得到正确的对象?

代码:

NSIndexPath *cellIndexPath=[NSIndexPath indexPathWithIndex:0];

ReminderCell *cell=(ReminderCell*)[self tableView:self.AroundersTableView cellForRowAtIndexPath:cellIndexPath];

[cell cancelDeletion];

崩溃日志:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid index path for use with UITableView. Index paths passed to table view must contain exactly two indices specifying the section and row. Please use the category on NSIndexPath in UITableView.h if possible.

cellForRowAtIndexPath: 覆盖:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Creating a default cell using "cellIdentifier"(NSString)
    ReminderCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell==nil) {
        cell=[[ReminderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    //Changing "cell"'s "index" to indexPath.row
    cell.index=(int)indexPath.row; //Crashes here

    cell.textLabel.text=@"Hello";

    //Returning cell
    return cell;
}

谢谢!

【问题讨论】:

  • 显示一些关于如何从cellForRowAtIndexPath获取单元格的代码
  • 您是否以编程方式创建 UITableView?
  • @DantePuglisi 更新帖子,请看一下
  • @BlackMagic 不,我正在使用故事板
  • 你能显示你的 CellForRowAtIndexPath 代码吗?还是你的 UITableView 是固定大小的?

标签: ios objective-c iphone uitableview cocoa-touch


【解决方案1】:

您应该将[NSIndexPath indexPathWithIndex:0]; 替换为[NSIndexPath indexPathWithIndex:0 inSection:0];

【讨论】:

    【解决方案2】:

    根据您上面显示的错误,您没有从 cell for row 方法中获取单元格,因为您创建的索引路径不正确。尝试使用[NSIndexPath indexPathForRow:0 inSection:0](注意:您需要更改 0 以反映您想要的单元格。

    【讨论】:

      【解决方案3】:

      您的 CellForRowAtIndexPath 应该返回 ReminderCell 而不是 UITableViewCell

      所以它应该从这个开始:

      -(ReminderCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
      

      【讨论】:

      • 我无法更改cellForRowAtIndexPath,它是一个委托函数
      • 是的,你可以,我已经做过很多次了。你仍然返回一个 UITableViewCell,只是它的一个子类
      【解决方案4】:

      将您的单元格定义为 ReminderCell

      ReminderCell *cell = [self.AroundersTableView cellForRowAtIndexPath:cellIndexPath];
      

      【讨论】:

      • 已更新,现在应该可以调用 [cell cancelDeletion];
      • 还是同样的问题,更新帖子请看
      • ReminderCell 中的索引是否定义为 Indexpath?你只向它发送一个值,indexpath 包含两个值
      • @FS.O cell.index = indexPath;
      【解决方案5】:

      您将cell 声明为UITableViewCell,如果您希望它是那种类型,请将其声明为ReminderCell

      【讨论】:

      • 还是同样的问题,更新帖子请看
      猜你喜欢
      • 2023-01-16
      • 2015-05-31
      • 1970-01-01
      • 2012-08-12
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多