【问题标题】:iOS dynamical height of UITableViewCell and heightForRowAtIndexPathiOS UITableViewCell 和 heightForRowAtIndexPath 的动态高度
【发布时间】:2015-07-10 08:55:00
【问题描述】:

我在一个大型项目中为我的新 UITableViewCells 使用自动布局。

我有一个 TableView 自动计算每一行的高度,我不使用委托函数heightForRowAtIndexPath

我已经声明了估计的行高:

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension

我的问题是:在另一个 TableViewController 上有很多 UITableViewCells,我需要以编程方式在 heightForRowAtIndexPath 中声明单元格的高度。我知道将所有单元格转换为使用独特的解决方案会更好,但是在这个项目中有很多不同的单元格,所以我想使用一种解决方法并将动态计算的高度与自动布局和编程计算的行相结合高度。

这可能吗?

【问题讨论】:

    标签: ios objective-c iphone uitableview


    【解决方案1】:

    如果您使用的是 iOS 8 及更高版本,则无需动态计算高度。自动布局将为您完成所有工作。但是如果你使用的是低于 IOS 8 的版本,则需要计算单元格高度。

    对于 IOS 8:

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return UITableViewAutomaticDimension;
    }
    

    并在您的控制器中添加以下代码:

    tableView.estimatedRowHeight = 400.0
    tableView.rowHeight = UITableViewAutomaticDimension
    

    estimatedRowHeight 应该是您单元格的最大高度。

    谢谢

    【讨论】:

      【解决方案2】:

      使用boundingRectWithSize 动态计算内容的高度。 如果您有一个动态的UILabel,您可以使用以下内容:

      - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
      
         /* Check Content Size and Set Height */
          CGRect answerFrame = [YOUR_LABEL.text boundingRectWithSize:CGSizeMake(240.f, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:[UIFont fontWithName:@"" size:14.0f]} context:nil];
      
          CGSize requiredSize = answerFrame.size;
      
          return requiredSize.height;
      }
      

      【讨论】:

        【解决方案3】:

        你可以试试这个。

        - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
            {
             int topPadding = cell.yourLabel.frame.origin.x;
             int bottomPadding = cell.frame.size.heigth-(topPadding+cell.yourLabel.frame.size.height);
             NSString *text = [DescArr objectAtIndex:[indexPath row]];
             CGSize maximumSize = CGSizeMake(cell.yourLabel.frame.size.width, 9999);
             CGSize expectedSize = [text sizeWithFont:yourCell.yourLabel.font constrainedToSize:maximumSize lineBreakMode:yourCell.yourLabel.lineBreakMode];
        
             return topPadding+expectedSize.height+bottomPadding;
        }
        

        【讨论】:

        • 问题是,我里面不只有一个 UILabel。但正如我所见,动态高度仅适用于 iOS8 及更高版本 - 所以当我想支持 iOS 8 时,我必须以编程方式计算高度,对吗?
        • @brokedid 是的,您总是必须以编程方式计算高度
        • 你好。如果我的屏幕高度是~700,但是从标签计算的高度是1000,那么我的标签可以显示所有文本,因为返回高度1000不起作用
        猜你喜欢
        • 2013-09-02
        • 2013-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-27
        • 1970-01-01
        • 1970-01-01
        • 2019-10-12
        相关资源
        最近更新 更多