cmii
cmii

Reputation: 3636

Why is my uitableview cut off with too many cells ? (swift)

I have a view controller with an uitableview to display some comments. I use storyboard and autolayout.

The height of cells depends on the content.

When I have many cells, my tableview is cut off, and not displayed fully. But it's correct with less cells.

In viewDidLoad :

self.commentsTableView.estimatedRowHeight = 93.0
self.commentsTableView.rowHeight = UITableViewAutomaticDimension

In viewDidAppear, I tried 2 approaches, first with the height constraint :

 override func viewDidAppear(animated: Bool) {

     super.viewDidAppear(animated)

     self.commentsTableView.removeConstraint(self.tableViewHeightConstraint)
     self.tableViewHeightConstraint = NSLayoutConstraint(item: self.commentsTableView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: self.commentsTableView.contentSize.height)
     self.commentsTableView.addConstraint(self.tableViewHeightConstraint)

     self.commentsTableView.setNeedsUpdateConstraints()
     self.commentsTableView.updateConstraintsIfNeeded()
}

I tried also with the height of the frame (without height constraint) :

 override func viewDidAppear(animated: Bool) {

    super.viewDidAppear(animated)

    var frame:CGRect = self.commentsTableView.frame
    frame.size.height = commentsTableView.contentSize.height
    self.commentsTableView.frame = frame
}

I have exactly the same result with the 2 approaches. When there are too many cells, the tableview is not displayed fully.

EDIT

A screenshot. In blue it's my scrollview.

my taleview

Upvotes: 0

Views: 1548

Answers (1)

cmii
cmii

Reputation: 3636

I found a solution.

In my viewDidAppear, I set first the frame of the tableview depending its content size, then I set the size of the scrollview with the height of the tableview.

The solution is to do the opposite, first set the scrollview to the content size of the tableview, then adjust the tableview with the height of the scrollview. And it works !

override func viewDidAppear(animated: Bool) {

    super.viewDidAppear(animated)

    self.scrollView.contentSize=CGSizeMake(self.scrollView.frame.size.width, self.commentsTableView.frame.origin.y + commentsTableView.contentSize.height)

    var frame:CGRect = self.commentsTableView.frame
    frame.size.height = scrollView.contentSize.height
    self.commentsTableView.frame = frame

}

Upvotes: 0

Related Questions