Autosizing UITableViewCell: change height of a view inside a custom cell

2.1k views Asked by At

I searched a lot for a solution but can't find anything to solve this particular case.

I created a custom cell in a UITableView, with these elements in order from top with the constraints:

  • imageview (constraints top screen, fixed width, fixed height, centered horizontal)
  • top-label (constraints top imageview, fixed width, centered horizontal) Line set to 0.
  • view (constraints top label, fixed width, centered horizontal) The height is set to 0.
  • button (constraints top view, fixed width, fixed height, centered horizontal)
  • bottom-label (constraints top view, constraints bottom screen, fixed width, fixed height, centered horizontal)

The cell is autosized in height correctly, also if I insert a text for top-label very long.

Now I want to attach an action to the button to enable the resize in height of the view, like an accordion. So I'm trying to change the height with no success, anything change also if I reload the tableview. I tried to set a constraints to the height of the view, but If I change that all the content move but the height of the cell doesn't change.

The only way I can have the view changing the height is setting the the rowheight of the table, but that change all the cells of the table and I want to open the view of only one cell.

Is there another way to do that?

Thanks in advance Ale

EDIT:

For clearance I've solved using the delegate method suggested by noobular, setting the view to 0 height permit to have that expanded when the height of the cell change.

2

There are 2 answers

4
noobular On BEST ANSWER

Edit: For auto sizing cells where you want UIKit to automatically calculate the height, I would suggest researching UITableViewAutomaticDimension

Implement this method for your tableView delegate: tableView:heightForRowAtIndexPath:

1
Ash On

I achieved a similar effect by these methods. First, I determine a constraint that will represent the height of my cell. I'm using the height constraint of a decorative bar on the left hand side that's pinned to the top and bottom of the cell. It's important that this constraint belong to an object that is a child of the cell's content view and that will be on-screen in both open and closed states. This constraint is connected to a property on the cell it will control.

When I want to change the height of the cell, i.e. to 100, I can do so as follows:

cell.heightConstraint.constant = 100.0
cell.layoutIfNeeded()
tableView.beginUpdates()
tableView.endUpdates()

The calls to beginUpdates and endUpdates force the tableView to layout its cells again, thus expanding or contracting the cell. Note that I'm actually calling the first two lines in the cell's own setSelected:animated: function and the remaining two in the table view controller's tableView:didSelectCellAtIndexPath: method. This has the effect of expanding a cell when it is selected.