Set UITableView's height to the height of its content with Auto Layout

前端 未结 7 1418
野的像风
野的像风 2020-12-04 13:40

I have a View which has two labels and a Table View inside it. I want label 1 to always stay above my Table View and label 2, to be below the Table View. The problem is that

7条回答
  •  天命终不由人
    2020-12-04 14:05

    The below code worked for me.

    1. Create an outlet for tableViewHeight.
    @IBOutlet weak var tableViewHeight: NSLayoutConstraint!
    var tableViewHeight: CGFloat = 0  // Dynamically calcualted height of TableView.
    
    1. For the dynamic height of the cell, I used the below code:
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return tableView.estimatedRowHeight
    }
    
    1. For height of the TableView, with dynamic heights of the TableView Cells:
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        print(cell.frame.size.height, self.tableViewHeight)
        self.tableViewHeight += cell.frame.size.height
        tableViewBillsHeight.constant = self.tableViewHeight
    }
    

    Explanation:

    After the TableView cell is created, we fetch the frame height of the cell that is about to Display and add the height of the cell to the main TableView.

提交回复
热议问题