本文介绍了获取tableView:heightForRowAtIndexPath:发生后tableView:cellForRowAtIndexPath:?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些UITableViewCells需要改变它们的高度取决于字符串里面的长度。我计算 tableView:cellForRowAtIndexPath:中的必要高度,然后将它存储在一个变量( self.specialRowHeight )。然后我有:

I've got some UITableViewCells that need to change their height depending on the length of the strings inside. I'm calculating the necessary height inside tableView:cellForRowAtIndexPath:, and then storing it in a variable (self.specialRowHeight). Then I've got:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == SPECIAL_SECTION) {
        return self.specialRowHeight;
    }
    else {
        return 44;
    }
}

除了似乎在 tableView:cellForRowAtIndexPath:位,因此它始终为零。

Except that seems to be getting called before the tableView:cellForRowAtIndexPath: bit, so it's always zero.

有一种方法,是吗?

谢谢!

推荐答案

这里:

最初我很确定高度计算被绑定到 tableView:cellForRowAtIndexPath:不能移动到别处。但是,通过一系列的重组,我能够把这些东西从那里拿到 tableView:heightForRowAtIndexPath:,这解决了一切。

Originally I was pretty sure that the height calculations were tied to the tableView:cellForRowAtIndexPath: method, and couldn't be moved elsewhere. With a bunch of restructuring, though, I was able to get that stuff out of there and into tableView:heightForRowAtIndexPath:, which solves everything.

对于试图获得自动调整高度的单元格工作的任何人,以下是一些可能有帮助的代码:

For anyone else who's trying to get auto-height-adjusted cells to work, here's some code that might help:

// Inside tableView:cellForRowAtIndexPath:
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = self.numberOfTextRows;
// numberOfTextRows is an integer, declared in the class

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

    CGSize theSize = [theObject.theStringToDisplay sizeWithFont:[UIFont systemFontOfSize:18.0f] constrainedToSize:CGSizeMake(265.0f, 9999.0f) lineBreakMode:UILineBreakModeWordWrap];
    // This gets the size of the rectangle needed to draw a multi-line string
    self.numberOfTextRows = round(theSize.height / 18);
    // 18 is the size of the font used in the text label
    // This will give us the number of lines in the multi-line string

    if ((indexPath.section == FIXED_HEIGHT_SECTION) || (self.numberOfTextRows < 2)) {
        return 44;
        // 44 is the default row height; use it for empty or one-line cells (or in other table sections)
    } else {
        return theSize.height + 16;
        // 16 seems to provide a decent space above/below; tweak to taste
    }
}

如果你能想到更准确方式来计算适当的细胞高度,我都耳朵。 :)

If you can think of a more accurate way to calculate the proper cell height, I'm all ears. :)

这篇关于获取tableView:heightForRowAtIndexPath:发生后tableView:cellForRowAtIndexPath:?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:40