如何使用Autolayout动态设置UITableView单元格的高度?

时间:2015-10-02 12:06:02

标签: ios uitableview autolayout

我在内容视图中选择了两个视图。 “后容器视图”(红色背景)的高度根据标签的高度动态计算(全部使用Autolayout完成)。

现在我希望如果“Post Container View”(红色背景)的高度增加,那么单元格视图的高度会自动增加。我想使用autolayout来做到这一点。

我想使用Autolayout计算UITableview单元格的高度。怎么做?

单元格高度=后期容器视图(根据标签高度灵活)+图像容器视图高度(300修复)

我见过这种方法,但不知道如何在我的代码中实现?

- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell
{

    sizingCell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.MyTableView.frame), CGRectGetHeight(sizingCell.bounds));

    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];

    CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return size.height + 1.0f; // Add 1.0f for the cell separator height
}

3 个答案:

答案 0 :(得分:1)

考虑到自动布局配置,您想计算高度,还是使用tableView计算高度本身?

为此,请不要实现委托方法 heightForRowAtIndexPath ,而是 estimatedHeightForRowAtIndexPath (使用您想要的任何值)。

tableView将考虑应用自动布局约束来确定单元格的高度。 请注意,有时您需要在更新后在单元格上调用 layoutIfNeeded 。 (例如 cellForRowAtIndexPath

答案 1 :(得分:1)

计算细胞高度:

CGFloat height ; // take global variable

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
      height = cell.PostContainerView.frame.size.height ;
}


- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    height = height + 300 //(300 is Fix height of Image Container View ) ;
    return height ;
}

答案 2 :(得分:0)

将此Extension类用于字符串:

import UIKit

extension String {       
    func sizeOfString (font: UIFont, constrainedToWidth width: Double) -> CGSize {
        return NSString(string: self).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
            options: NSStringDrawingOptions.UsesLineFragmentOrigin,
            attributes: [NSFontAttributeName: font],
            context: nil).size
    }   }

UITableView委托计算UILabel宽度:

 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {        
        let item = "hkxzghkfjkgjkfxkj jjhghdjajfjkshgjkhkkn jhkhhgdfgjkhsfjkdghhhsxzgnfshgfhk jhsfgfhjfhghj "
        let widthOfLabel = Double(view.frame.size.width) - 30
        let textHeight = item.sizeOfString(UIFont.systemFont(14), constrainedToWidth: widthOfLabel)
             return (padding + textHeight.height)
     }
相关问题