尝试自动调整大小的UITableViewCell会导致未知错误

时间:2012-03-22 01:51:24

标签: objective-c ios

我希望tableView第1部分中的单元格自动调整大小,在仔细阅读堆栈溢出后,我找到了一个相当好的接受答案并试图实现它。但是,使用以下代码会导致系统崩溃而不会出现错误。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath section] == 0) {
        return 80;
    }
    else if([indexPath section] == 1){
          UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//        NSLog(@"%@", cell.textLabel.text);
//        NSString *cellText = cell.textLabel.text;
//        
//        UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
//        CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
//        CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
//        
//        return labelSize.height + 20;
        NSLog(@"Hello");
        return 120;

    }

    return 44;

}

但是如果我删除了单元格的创建,就像这样:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath section] == 0) {
        return 80;
    }
    else if([indexPath section] == 1){
//        NSLog(@"%@", cell.textLabel.text);
//        NSString *cellText = cell.textLabel.text;
//        
//        UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
//        CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
//        CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
//        
//        return labelSize.height + 20;
        NSLog(@"Hello");
        return 120;

    }

    return 44;

}

错误停止,应用运行正常。注意包含NSLog,当包含单元格创建时,这会导致堆栈溢出,我认为,因为控制台加载了重复的“Hello”。当删除单元格创建时立即停止,并且Hello只按预期说一次。不介意其余的代码,我最关心的是为什么添加这一行代码会引起它的反应。

1 个答案:

答案 0 :(得分:2)

你有一个所谓的infinite recursion.在外行人的术语中,它意味着UITableview的委托方法

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

调用[tableView cellForRowAtIndexPath:indexPath];时调用

。因为你已经在它最终调用的方法中调用了它,所以你创建了一个很好的无限循环,从而打印出700万个NSLog并崩溃你的应用程序(一段时间后)。