动态tableHeaderView无法正常工作

时间:2018-12-31 08:43:25

标签: ios swift xcode autolayout tableview

我有一个tableHeaderView,它应该根据其内容具有动态高度。

我尝试使用systemLayoutSizeFitting&sizeToFit方法来设置表格视图的新高度,不幸的是,这似乎工作得很好,但是却不是我想要的(动态UI之一被裁剪了)。我尝试将要动态设置的UI的内容压缩抗性优先级设置为(1000),但是它的效果不佳..每次至少裁剪一个UI时。

view simulator output image

another simulator output image

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var podView: PodView!
@IBOutlet weak var postCaption: UILabel!

var pod: Pod!

override func viewDidLoad() {
    super.viewDidLoad()

    //set header view
    podView.setPod(image: pod.image, title: pod.title, description: pod.description, viewWidth: UIScreen.main.bounds.width)
    podView.sizeToFit()
    postCaption.text = pod.description
    postCaption.sizeToFit()
    let height = tableView.tableHeaderView!.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
    tableView.tableHeaderView!.frame.size.height = height
}

编辑:约束:

view constraint

label Constraint

2 个答案:

答案 0 :(得分:0)

尝试执行以下步骤以创建动态tableview标头单元格:-

1-从情节提要的表视图中添加一个UItableViewCell

2-根据您的要求创建tableView header UI。

3-根据需要,将类创建为TableViewHeaderCell,您想要在标题单元格中显示什么。

4-然后在ViewController类中实现headerview delegate method

/**
    Tableview header method 
*/
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

}

5-在这种方法中,您要创建TableViewHeaderCell对象并像这样返回cell content View

    /**
    Table Header view cell implement and return cell content view when you create cell object with you identifier and cell name after that you have to mention height for header cell
    */
  override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
                let cell = tableView.dequeueReusableCell(withIdentifier: "Cell Identifier") as! CellName
                return cell.contentView
   }

6-实施Tableview header height method

/**
Here you can specify the height for tableview header which is actually your `TableViewHeader Cell height`
*/
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
       //For eg
        return 100
    }

通过此步骤,您还可以实现动态页眉视图单元格和页脚视图单元格,但是对于页脚视图单元格,请实现Tableview页脚视图委托方法

>

谢谢

答案 1 :(得分:0)

具有TableHeaderView的动态高度。将以下代码添加到您的viewController中。它将像魅力一样工作。

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let headerView = tableView.tableHeaderView {
        let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
        var headerFrame = headerView.frame

        //Comparison necessary to avoid infinite loop
        if height != headerFrame.size.height {
            headerFrame.size.height = height
            headerView.frame = headerFrame
            tableView.tableHeaderView = headerView
        }
    }
}

注意:请确保tableHeaderView具有适当的AutoLayout约束以获取适当的高度。

相关问题