获取tableView:heightForRowAtIndexPath:在tableView之后发生:cellForRowAtIndexPath:?

Tri*_*riz 14 iphone cocoa-touch uitableview

我有一些UITableViewCells需要根据内部字符串的长度来改变它们的高度.我正在计算内部的必要高度tableView:cellForRowAtIndexPath:,然后将其存储在变量(self.specialRowHeight)中.然后我有:

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

除了似乎在tableView:cellForRowAtIndexPath:比特之前被调用,所以它总是为零.

有没有办法解决这个问题,或者采取不同的方式来做到这一点?

谢谢!

Tri*_*riz 11

要在这里回答我自己的问题:

最初我很确定高度计算与tableView:cellForRowAtIndexPath:方法有关,并且无法移动到其他地方.然而,通过一系列重组,我能够从那里获得那些东西tableView:heightForRowAtIndexPath:,这解决了一切.

对于那些试图让自动调整高度的单元格起作用的人来说,这里有一些可能有用的代码:

// 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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你能想出一个更准确的方法来计算合适的细胞高度,那我就是耳朵.:)

  • cell.txtLabel.numberOfLines = 0; //这将显示所有行 (6认同)