21
votes

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.

1
i guess you shouldn't call tableview.frame.size = tableview.contentSize in cellForRowAtIndexPath - aaisataev
@aaisataev Ya correct. Check out my answer - user5479794

1 Answers

53
votes

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