【问题标题】:Current cell height inside the heightForRowAtIndexPath?heightForRowAtIndexPath 内的当前单元格高度?
【发布时间】:2013-04-10 13:46:43
【问题描述】:

我有一张带有静态单元格的表格。对于一个单元格,我想根据标签的高度(在该单元格内)更改其高度,同时保持所有其他单元格的高度不变。如何获取当前单元格的高度?或者也许有更好的方法?

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([indexPath section] == 2) {
        return self.myLabel.frame.origin.y *2 + self.myLabel.frame.size.height;
    } else {
        return ...; // what should go here, so the cell doesn't change its height?
    }
}

【问题讨论】:

  • 你的单元格的默认高度在那里。 44 如果你没有改变任何东西。
  • 您也可以使用 UIKIt 对 NSString 方法的扩展 sizeWithFont: 计算单元格实际需要的标签高度。

标签: ios objective-c uitableview


【解决方案1】:

您可以致电:

[super tableView:tableView heightForRowAtIndexPath:indexPath] 

在 else 块中,因此您不必担心是否更改了默认高度。

【讨论】:

    【解决方案2】:

    您可以获取/设置默认高度tableView.rowHeight,或者您可以在更改单元格高度之前存储您的高度,这样您就可以从某个变量中获取默认高度;

    【讨论】:

      【解决方案3】:

      请做这个

      if ([indexPath section] == 2)
      {
          if(indexPath.row == 1)
               return self.myLabel.frame.origin.y *2 + self.myLabel.frame.size.height; 
          else 
               tableView.rowHeight
      }
      

      【讨论】:

        【解决方案4】:

        @talnicolas 很好的答案,这里是 Swift 3:

        override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            if indexPath.section == 2 {
                let easy = self.myLabel.frame
                return easy.origin.y *2 + easy.size.height
            } else {
                return super.tableView(tableView, heightForRowAt: indexPath)
            }
        }
        

        【讨论】:

          【解决方案5】:

          您也许想在受限宽度下计算标签的高度。在这种情况下,您可以创建这样的方法:

          - (CGFloat)textHeightOfMyLabelText {
              CGFloat textHeight = [self.myLabel.text sizeWithFont:self.myLabel.font constrainedToSize:LABEL_MAX_SIZE lineBreakMode:self.myLabel.lineBreakMode].height;
              return textHeight;
          }
          

          并在- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 中使用结果。 不要忘记添加标签的边距值。

          【讨论】:

            【解决方案6】:
            - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
            {
                if (indexPath.section == youSectionNumber)
                {
                    if (indexPath.row == numberOfrow)
                    {
                        return self.myLabel.frame.origin.y *2 + self.myLabel.frame.size.height;
                    }
                }
            
                  return 44; // it is default height of cell;
            }
            

            【讨论】:

              猜你喜欢
              • 2012-08-08
              • 2011-06-16
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-10-22
              • 1970-01-01
              相关资源
              最近更新 更多