user5479794
user5479794

Reputation:

Dynamic height TableView in a Scroll View

I am designing a page having a scroll view and above it a table view(scroll disabled). For doing this I have referred answers in this question - Make UITableView not scrollable and adjust height to accommodate all cells ,but wasn't successful.

Hierarchy of views along with provided constraints-

-Main View

-Scroll view
pinned to all sides of main view(0,0,0,0), constraint to margins

-Content View

pinned to scroll view(0,0,0,0),equal width to main view,equal height to main view(priority - 250)

-Table view inside content view

scroll disabled,having 50 point spaces from all sides,Height(>=),bottom spacing 50(relation >=).I have put greater than equal so as to increase height dynamically.

Now when I populate my table view I use the code as

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableview.dequeueReusableCellWithIdentifier("cellreuse", forIndexPath: indexPath) 
        cell.textLabel?.text = name[indexPath.row]

        tableview.frame.size = tableview.contentSize

        return cell
    }

So when I run my code, it increases the tableview frame but doesn't stretch the content size and it just becomes weird as my scroll view doesn't scroll to the end of the table view neither my table view obeys the auto layout constraints.

Upvotes: 22

Views: 25205

Answers (3)

Mansur76
Mansur76

Reputation: 59

Had the same issue and resolved it by doing the following:

  1. Create an outlet of the height constraint for the table view with a priority of 1000

    @IBOutlet private weak var tableViewHeight: NSLayoutConstraint!

  2. On viewDidLayoutSubview call layoutIfNeeded on the table view and then set the table view height constraint to the height of the content view

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        tableView.layoutIfNeeded()
        tableViewHeight.constant = tableView.contentSize.height
    }
    

Tested on iOS 14.1 and iOS 16.1

Upvotes: 0

Bilal Khan
Bilal Khan

Reputation: 1423

  1. Assign a table height. Let it be constant 0.
  2. Just add below lines.
    tableView.heightConstant.constant = CGFloat.greatestFiniteMagnitude
    tableView.reloadData()
    tableView.layoutIfNeeded()
    tableView.heightConstant.constant = tableView.contentSize.height
    

With this, you can easily achieve dynamic table height. Working on iOS 13, Swift 5.

Upvotes: 5

user5479794
user5479794

Reputation:

Just I needed to do this -

  • remove the line - tableView.frame.size = tableView.contentSize

  • Add a height constraint for table view.

  • Set priority to High

  • Create an outlet of the height constraint(Ctrl+Drag).

  • Wherever you need to reload data of your table, set the height constraint to tableview's content height.

tableHeightConstraint.constant = tableview.contentSize.height

Upvotes: 56

Related Questions