繁体   English   中英

UITableViewCell是Nil

[英]UITableViewCell is Nil

我确定这个问题有一个简单的答案,但我似乎无法找到它。 我的UITableViewController有以下代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell==nil)
    {
        NSLog(@"Cell is nil!");
    }

    return cell;
}

但是在我的日志输出中,我得到了

细胞是零!

然后立即

终止应用程序由于未捕获的异常'NSInternalInconsistencyException',理由是: 'UITableView的数据源必须返回从的tableView细胞:的cellForRowAtIndexPath:' *第一掷调用堆栈:(0x1b68d72 0x135fe51 0x1b68bd8 0xb0e315 0xcb373 0x63578 0xcb1d3 0xcff19 0xcffcf 0xb9384 0xc952e 0x691bc 0x13736be 0x215c3b6 0x2150748 0x215055c 0x20ce7c4 0x20cf92f 0x2171da2 0x1b4b4 0x1be63 0x2c2be 0x2cf9f 0x1f3fd 0x1ac5f39 0x1ac5c10 0x1adeda5 0x1adeb12 0x1b0fb46 0x1b0eed4 0x1b0edab 0x1b28f 0x1ce71 0x253d 0x2465)libc ++ abi.dylib:terminate调用抛出异常(lldb)

有谁知道为什么会这样,更重要的是,如何解决它?

提前致谢。

如果没有,你必须创建单元格,因为方法

[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

从表视图缓存返回未使用的单元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:NSIndexPath*)indexPath
{
   static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil)
   {
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
   }

   //configure cell

   return cell;
}

dequeueReusableCellWithIdentifier返回已创建的单元格,其中包含您传入的标识符(如果存在可以重复使用的单元格)。

如果没有,你负责创建一个。

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
                                   reuseIdentifier:kCustomCellID] autorelease];
}

是的,方法UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 意味着它将重用已经分配了CellIdentifier的单元格。但是你没有为这个标识符分配任何单元格,对于tableView,它将为屏幕分配一些单元格,然后它将重用具有标识符的单元格,如果你喜欢这样,你会发现它会起作用

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell==nil)
    {
        NSLog(@"Cell is nil!");
        cell = [[[UITableViewCell alloc] initWithSyle:UITableViewCellStyleNormal reuseIdentifier:CellIdentifier] autorelease];
    }

    return cell;
}

参加考试。

您是否为此课程使用interface builder 如果是这样,请不要忘记从表视图中进行引用。 我有同样的问题,这就是我的情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM