在为UITableViewCell加载自定义xib文件时,应用程序崩溃

时间:2013-03-15 12:11:24

标签: iphone ios uitableview

当我尝试加载自定义UITableViewCell应用程序崩溃时。我以前做了很多次,这次我也是这样做的。注释导致崩溃的部分代码(//这部分导致崩溃):

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


    static NSString *CellIdentifier = @"CustomTableCell";

    CustomTableCell *cell = (CustomTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

       // This part is causing crash
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomTableCell" owner:nil options:nil];

        cell = [topLevelObjects objectAtIndex:0];

    }

     return cell;

}

有CustomTableCell.h,CustomTableCell.m和CustomTableCell.xib。

CellIdentifier是CustomTableCell,nib名称没有空间问题。

错误的屏幕截图: enter image description here

崩溃的原因是什么?

5 个答案:

答案 0 :(得分:1)

您是否在课程中检查了Custom Cell的连接而不是File的所有者。 ? enter image description here

答案 1 :(得分:0)

请尝试以下代码:

#import "customCell.h"

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   // Configure the cell.
   static NSString *CustomCellIdentifier = @"customCell";
   customCell *cell = (customCell *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];

   if (cell == nil)
   {
      NSArray *nib;
      nib = [[NSBundle mainBundle] loadNibNamed:@"customCell" owner:self options:nil];

      for (id oneObject in nib)
          if ([oneObject isKindOfClass:[customCell class]])
             cell = (customCell *)oneObject;

      cell.lbl.text = @"Hello";
   }
   return cell;
}

希望它会帮助你。

答案 2 :(得分:0)

试试这个..

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

   NSArray *nib;
   for (UIControl *subview in cell.contentView.subviews) {
      [subview removeFromSuperview];
   }

   if(cell == nil)
   {
       nib = [[NSBundle mainBundle] loadNibNamed:@"CustomTableCell" owner:self options:nil];

       for(id oneobject in nib)
       {
          if([oneobject isKindOfClass:[CustomTableCell class]])
          {
             cell = (CustomTableCell *)oneobject;
          }
       }
   }
}
希望它有所帮助..

答案 3 :(得分:0)

到目前为止代码看起来还不错。可能的问题是,您没有在编辑器中将xib链接到您的自定义类。如果是这样,您可能会遇到问题,某些链接的Outlet不存在(或者说,它取决于错误)。

您可以在“自定义类”下的编辑器中链接自定义表格视图单元格。通过单击自定义单元格上的xib文件编辑器来执行此操作(在左侧部分中,您可以找到“对象”部分,在此下方,您应找到表格视图单元格)。 如果您打开了属性编辑器,请单击第三个选项卡(这样您就可以看到,您可以在其中设置自定义类。输入您的类的名称(在您的情况下,它的“CustomTableCell”)。单击右侧的右箭头如果您的自定义类存在,则输入的类进行验证。重新编译(可选make make clean),它应该可以正常工作。

答案 4 :(得分:0)

解决。

我为自定义单元格创建了新的xib文件,现在一切正常。

相关问题