iOS自定义单元可扩展 - 索引0问题

时间:2012-12-07 20:19:17

标签: objective-c ios uitableview custom-cell

感谢您的帮助。 我有一个自定义单元格,我使用以下代码展开。但是,第一个单元格(索引0)总是在ViewControllers启动时扩展?

我错过了什么?你如何在发布时将它们全部展开,并且仅在选择时进行扩展。

非常感谢。

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        CustomCellCell *cell;
        static NSString *cellID=@"myCustomCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];

        if (cell == nil) 
        {
            NSArray *test = [[NSBundle mainBundle]loadNibNamed:@"myCustomCell" owner:nil options:nil];
            if([test count]>0)
            {
                for(id someObject in test)
                { 
                    if ([someObject isKindOfClass:[CustomCellCell class]]) {
                        cell=someObject;
                        break;
                    }
                }
            }
        }

        cell.LableCell.text = [testArray objectAtIndex:[indexPath row]];
        NSLog( @"data testarray table %@", [testArray objectAtIndex:[indexPath row]]);
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }

    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        self.selectedRow = indexPath.row;
        CustomCellCell *cell = (CustomCellCell *)[tableView cellForRowAtIndexPath:indexPath];

        [tableView beginUpdates];
        [tableView endUpdates];

        cell.buttonCell.hidden = NO;
        cell.textLabel.hidden = NO;
        cell.textfiledCell.hidden = NO;
        cell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        cell.clipsToBounds = YES;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        if(selectedRow == indexPath.row) {
            return 175;
        }

        return 44;
    }

2 个答案:

答案 0 :(得分:1)

这是因为selectedRow的默认值为零。您需要将其初始化为

selectedRow = NSIntegerMax; //or selectedRow = -1;

或其他一些默认值。您可以使用viewDidLoad方法左右添加它。每当声明一个int类型变量时,默认值为零。因此,如果你有一个需要检查零的场景,例如在上面的例子中,你应该将它默认为一个根本不会被使用的值。可以使用负值或NSIntegerMax

答案 1 :(得分:0)

我猜测selectedRow是一个整数实例变量。该整数以值0开始生命。由于第一个表格单元格为第0行,即使您没有有意设置它,它也会匹配selectedRow。

解决此问题的一种方法是将selectedRow存储为NSIndexPath而不是整数。

然后你可以这样做:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if([selectedRow isEqual:indexPath]) {
        return 175;
    }
    return 44;
}

因为selectedRow默认为nil,所以你不会得到错误的匹配。如果您决定稍后使用部分,它也会更灵活。