Swift UITableViewAutomaticDimension is not working

前端 未结 4 858
时光取名叫无心
时光取名叫无心 2021-01-28 18:03

I have got a table in my Swift project like this

var tableView: UITableView! 
tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
ta         


        
相关标签:
4条回答
  • 2021-01-28 18:12

    You need intrinsic cell size for this to work. Delete heightForRowAt entirely. Your constraints in your cell should determine the cell size, this means your constraints should be at least pinned from top and bottom. Add the following code after setting the rowHeight:

    tableView.estimatedRowHeight = 250
    
    0 讨论(0)
  • 2021-01-28 18:18

    You must delete the -heightForRow method and set on the table view an estimatedRowHeight.
    The estimatedRowHeight is used to calculate the bar size etc of the TV, so it should be a real value closest as possible to an average size of the table view cell height.
    Now, if you are using auto layout and constraints are set correctly you should see a correct resize of your UITableViewCell. To set correctly the constraints inside the TVC you should think to place them in a way that they can control the size of your cell.
    For instance say that your TVC has just one label and that label has 4 constraints attached to its superview: top, bottom, trailing and leading with a fixed constant size. The UILabel instance has also the numberOfLines set to 0 (means that it can expand to fill all your text).
    When the autolayout engine starts to request the label intrinsicContentSize, the label will return a value that will fit all your text, the superview size will change the size according to that.
    If you fix the TVC to a specific height as you did before, the TVC can't expand itself.

    0 讨论(0)
  • 2021-01-28 18:26

    Pin the view's constraints to the superview's edges. Also call the estimatedRowHeight.. Remember to call a reload from the table to invoke height calculation for each cell to display.

    0 讨论(0)
  • 2021-01-28 18:30

    I had problems with constraints so here is what i did.
    First i added heightForRowAt

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    

    Then i created a variable

    let tableViewHeight  = postTexts.count*100
    

    And put that in my height constraint

        tableView.anchor(PostsDiv.bottomAnchor, left:view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 40, leftConstant: 15, bottomConstant: 0, rightConstant: 15, widthConstant: 0,heightConstant: CGFloat(tableViewHeight))
    

    And it works pretty well for me

    0 讨论(0)
提交回复
热议问题