Collapsable Table Cells [Swift 3] [duplicate]

非 Y 不嫁゛ 提交于 2019-12-18 09:43:25

问题


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:


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:



来源:https://stackoverflow.com/questions/40198826/collapsable-table-cells-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!