Collapsable Table Cells [Swift 3] [duplicate]

2019-01-29 13:42发布

This question already has an answer here:

I am trying to recreate the collapsable date picker that the calendar app uses when creating a new event. I've put an example of what I'm trying to do on github

In short, I've created a static table, added three cells. The first cell is for the date, and contains a button to toggle the second cell. The second cell is the date picker. The third cell is arbitrary. In the code I'm trying to set the height of the table cell (and the date picker if needed) to zero, and then toggle the size whenever the user clicks the button. No matter what I've tried, I can't a) get the cell to collapse without some sort of gap, and 2) get the animation to smoothly transition from expanded to collapsed and back again.

Edit: This question is not the same as the duplicate answer, in that I wanted to expand a separate table cell and not the same cell as being selected. But, I personally can live with using a same-cell expansion. I also updated my github project so future people can see a working example.

1条回答
仙女界的扛把子
2楼-- · 2019-01-29 14:11

It's very simple; you are probably over-thinking things here. This functionality is built in; Apple wants you to be able to expand and contract a cell. You just aren't using the API Apple has provided. Use it! Here's how.

The date picker cells are always present. But their height is zero (and their clipsToBounds is true) so you don't see them. So implement heightForRowAtIndexPath to return zero for those cells.

To show a date picker cell, change what heightForRowAtIndexPath returns (this is easiest if you have a property that holds this value, so you can just change the property value and have heightForRowAtIndexPath read it from there) and say:

    self.tableView.beginUpdates()
    self.tableView.endUpdates()

That's all there is to it!

Here's a quick demo I made. The red and orange things are cells. The table has three cells but the second one, containing the date picker, starts out with zero height:

enter image description here

查看更多
登录 后发表回答