skip to Main Content

I have a TableView in a ScrollView. I set some constraint and auto layout to dynamic cell and dynamic height of table view. But i get some problems with each cell, some of each cell don’t show all of content. Any body help?

My information label

And auto layout of number in right of information label

Autolayout of number label

Code of table view

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

Code for dynamic tableview

    override func updateViewConstraints() {
        tableHeightConstraint.constant = tableView.contentSize.height
        super.updateViewConstraints()
    }

My problem now:
Result of code

I’m stuck fews day. Many thanks.

3

Answers


  1. add this 2 lines in viewDidLoad

    tableView.estimatedRowHeight = 68.0
    tableView.rowHeight = UITableViewAutomaticDimension
    

    check this example as well for constraints

    https://github.com/iDhaval/TableCellDynamicHeight

    Login or Signup to reply.
  2. There are few things you can do here.

    • Try setting text label’s bottom constraint to "Greater than or Equal".
    • Calling layoutIfNeeded() after setting tableView height constraint
    Login or Signup to reply.
  3. UILabel has an attribtute called "numberOfLines" and as default it is set to 1, which gives one line in a cell. We can set as many lines as We want but setting this value to 0 will allow us to adapt the number of lines in our cell to the number of lines we actually need. So add a line of code: cell.textLabel?.numberOfLines = 0 to the func. All should looks like this:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
               let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
               cell.textLabel?.numberOfLines = 0
               return cell
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search