How to create dynamic tableview cell with dynamic tableview height in iOS

前端 未结 4 787
太阳男子
太阳男子 2021-01-26 23:14

I want to increase tableview cell and tableview height based on content. Suppose tableview contain 2 record and his 1st cell height is 100 and 2nd cell height is 25 then tablevi

4条回答
  •  太阳男子
    2021-01-26 23:37

    Solution in swift 3

    Step 1. Set the top, bottom, leading and trailing constraints (do not make it constant height, but do set a constant height constraint as of now). Now we gonna change this height dynamically based on the number of cells and its height.

    Step 2. Drag an outlet of that height constraint to the class, and copy this function anywhere in the class.

        func adjustHeightOfTableview() {
        let height: CGFloat = tableview.contentSize.height
        self.outLetOfTheHeightConstraint.constant = height
    
    }
    

    Step 3.

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        DispatchQueue.main.async {
                self.tableview.reloadData()
                self.perform(#selector(self.adjustHeightOfTableview))
            }
    }
    

提交回复
热议问题