根据它使用的UITableViewCell的类型更改heightForRowAtIndexPath?

Luk*_*uke 3 objective-c uitableview ios

cellForRowAtIndexPath,我使用随机产生两个不同的自定义的一个UITableViewCell类型,我们姑且称之为LCImageCellLCTextCell(一个包含图像,一个包含一些文本,这是随机的,这将每行中显示).这基本上是:

- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
    // Determine whether the cell should contain an image or text..
    BOOL isCellAnImage;
    int randomChanceOfImageAppearing = arc4random() % 5;
    if (randomChanceOfImageAppearing == 4) isCellAnImage = YES;
    else isCellAnImage = NO;

    // If the cell is going to contain an image..
    if (isCellAnImage) {
        LCIImageCell *imageCell = [tableView dequeueReusableCellWithIdentifier: @"ImageCell"];
        if (imageCell == nil) {
            imageCell = [[LCImageCell alloc] initWithStyle: UITableViewCellStyleValue1 reuseIdentifier: @"ImageCell"];
        }

        return imageCell;

    // Else the cell will contain text..
    } else {
        // Make and allocate the cell if necessary.
        LCTextCell *customCell = [tableView dequeueReusableCellWithIdentifier: @"CustomCell"];
        if (customCell == nil) {
            customCell = [[LCTextCell alloc] initWithStyle: UITableViewCellStyleValue1 reuseIdentifier: @"CustomCell"];
        }
        return customCell;
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要动态设置那些带文本(LCTextCell实例)的高度,这是正常的.我现在要集成图像单元格,我想知道如何让我heightForRowAtIndexPath知道所讨论的单元格是a LCImageCell还是a LCTextCell,这样我只能在有问题的单元格中应用高度调整LCTextCell.

我可以在设置高度之前访问应用高度的单元格吗?它甚至已经被那个时间点创建/分配/初始化了吗?

fol*_*ben 6

看似合乎逻辑的事情是-cellForRowAtIndexPath:从内部调用-tableView:heightForRowAtIndexPath:.然而,这是一种糟糕的形式(后者在前者之前被称为原因)并且可能导致性能问题(heightForRowAtIndexPath对于表中的每个单元,甚至是不可见的单元,每次显示表时都会调用).

相反,将单元格随机化移动到viewController生命周期的早期阶段.例如,假设您事先知道每个单元格类型的高度(并且您的tableView只有一个部分):

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];

    for (int i = 0; i < [self.tableView numberOfRowsInSection:0]; i++) {
        if (arc4random() % 5 == 4) {
            [mutableArray addObject:[LCImageCell class]];
        } else {
            [mutableArray addObject:[LCImageCell class]];
        }
    }

    self.cellTypes = [NSArray arrayWithArray:mutableArray];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.cellTypes objectAtIndex:indexPath.row] isEqual:[LCImageCell class]]) {
        [LCImageCell height];  // class method returns static height for an image cell
    } else {
        [LCTextCell height];   // class method returns static height for a text cell
    };
}
Run Code Online (Sandbox Code Playgroud)

如果高度是动态的,您也应该提前计算并存储.