{"id":15038038,"url":"https://github.com/jeantimex/ios-swift-collapsible-table-section","last_synced_at":"2025-05-16T18:07:56.998Z","repository":{"id":148194960,"uuid":"60026310","full_name":"jeantimex/ios-swift-collapsible-table-section","owner":"jeantimex","description":":iphone: A simple iOS Swift project demonstrates how to implement collapsible table section.","archived":false,"fork":false,"pushed_at":"2020-04-23T23:39:42.000Z","size":5367,"stargazers_count":1215,"open_issues_count":18,"forks_count":150,"subscribers_count":29,"default_branch":"master","last_synced_at":"2025-05-11T11:27:28.156Z","etag":null,"topics":["autosize","collapse","demo","ios-swift","swift4","tableview"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jeantimex.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2016-05-30T17:05:54.000Z","updated_at":"2025-04-20T05:17:00.000Z","dependencies_parsed_at":"2023-09-29T08:55:14.157Z","dependency_job_id":null,"html_url":"https://github.com/jeantimex/ios-swift-collapsible-table-section","commit_stats":{"total_commits":69,"total_committers":3,"mean_commits":23.0,"dds":0.05797101449275366,"last_synced_commit":"ed1677a1f5450f336a69bcc74fad255df3d5f5b0"},"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeantimex%2Fios-swift-collapsible-table-section","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeantimex%2Fios-swift-collapsible-table-section/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeantimex%2Fios-swift-collapsible-table-section/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeantimex%2Fios-swift-collapsible-table-section/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jeantimex","download_url":"https://codeload.github.com/jeantimex/ios-swift-collapsible-table-section/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254422894,"owners_count":22068695,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["autosize","collapse","demo","ios-swift","swift4","tableview"],"created_at":"2024-09-24T20:36:52.372Z","updated_at":"2025-05-16T18:07:56.965Z","avatar_url":"https://github.com/jeantimex.png","language":"Swift","funding_links":["https://paypal.me/jeantimex/3","https://opencollective.com/ios-collapsible-table-section"],"categories":[],"sub_categories":[],"readme":"# How to Implement Collapsible Table Section in iOS\n\n[![Language](https://img.shields.io/badge/swift-5-brightgreen.svg?style=flat)]()\n[![Backers on Open Collective](https://opencollective.com/ios-collapsible-table-section/backers/badge.svg)](#backers) \n[![Sponsors on Open Collective](https://opencollective.com/ios-collapsible-table-section/sponsors/badge.svg)](#sponsors) \n\nA simple iOS swift project demonstrates how to implement collapsible table section programmatically, that is no main storyboard, no XIB, no need to register nib, just pure Swift!\n\nIn this project, the table view automatically resizes the height of the rows to fit the content in each cell, and the custom cell is also implemented programmatically.\n\n![cover](https://user-images.githubusercontent.com/565300/33296371-1c17e332-d390-11e7-910b-947ed42fcbb3.gif)\n\n## How to implement collapsible table sections? ##\n\n#### Step 1. Prepare the Data ####\n\nLet's say we have the following data that is grouped into different sections, each section is represented by a `Section` object:\n\n```swift\nstruct Section {\n  var name: String\n  var items: [String]\n  var collapsed: Bool\n    \n  init(name: String, items: [Item], collapsed: Bool = false) {\n    self.name = name\n    self.items = items\n    self.collapsed = collapsed\n  }\n}\n    \nvar sections = [Section]()\n\nsections = [\n  Section(name: \"Mac\", items: [\"MacBook\", \"MacBook Air\"]),\n  Section(name: \"iPad\", items: [\"iPad Pro\", \"iPad Air 2\"]),\n  Section(name: \"iPhone\", items: [\"iPhone 7\", \"iPhone 6\"])\n]\n```\n`collapsed` indicates whether the current section is collapsed or not, by default is `false`.\n\n#### Step 2. Setup TableView to Support Autosizing ####\n\n```swift\noverride func viewDidLoad() {\n  super.viewDidLoad()\n        \n  // Auto resizing the height of the cell\n  tableView.estimatedRowHeight = 44.0\n  tableView.rowHeight = UITableViewAutomaticDimension\n  \n  ...\n}\n\noverride func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -\u003e CGFloat {\n  return UITableViewAutomaticDimension\n}\n```\n\n#### Step 3. The Section Header ####\n\nAccording to [Apple API reference](https://developer.apple.com/reference/uikit/uitableviewheaderfooterview), we should use `UITableViewHeaderFooterView`. Let's subclass it and implement the section header `CollapsibleTableViewHeader`:\n\n```swift\nclass CollapsibleTableViewHeader: UITableViewHeaderFooterView {\n    let titleLabel = UILabel()\n    let arrowLabel = UILabel()\n    \n    override init(reuseIdentifier: String?) {\n        super.init(reuseIdentifier: reuseIdentifier)\n        \n        contentView.addSubview(titleLabel)\n        contentView.addSubview(arrowLabel)\n    }\n    \n    required init?(coder aDecoder: NSCoder) {\n        fatalError(\"init(coder:) has not been implemented\")\n    }\n}\n```\n\nWe need to collapse or expand the section when user taps on the header, to achieve this, let's borrow `UITapGestureRecognizer`. Also we need to delegate this event to the table view to update the `collapsed` property.\n\n```swift\nprotocol CollapsibleTableViewHeaderDelegate {\n    func toggleSection(_ header: CollapsibleTableViewHeader, section: Int)\n}\n\nclass CollapsibleTableViewHeader: UITableViewHeaderFooterView {\n    var delegate: CollapsibleTableViewHeaderDelegate?\n    var section: Int = 0\n    ...\n    override init(reuseIdentifier: String?) {\n        super.init(reuseIdentifier: reuseIdentifier)\n        ...\n        addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(CollapsibleTableViewHeader.tapHeader(_:))))\n    }\n    ...\n    func tapHeader(_ gestureRecognizer: UITapGestureRecognizer) {\n        guard let cell = gestureRecognizer.view as? CollapsibleTableViewHeader else {\n            return\n        }\n        delegate?.toggleSection(self, section: cell.section)\n    }\n    \n    func setCollapsed(_ collapsed: Bool) {\n        // Animate the arrow rotation (see Extensions.swf)\n        arrowLabel.rotate(collapsed ? 0.0 : .pi / 2)\n    }\n}\n```\n\nSince we are not using any storyboard or XIB, how to do auto layout programmatically? The answer is `constraint anchors`.\n\n```swift\noverride init(reuseIdentifier: String?) {\n  ...\n  // Content View\n  contentView.backgroundColor = UIColor(hex: 0x2E3944)\n\n  let marginGuide = contentView.layoutMarginsGuide\n\n  // Arrow label\n  contentView.addSubview(arrowLabel)\n  arrowLabel.textColor = UIColor.white\n  arrowLabel.translatesAutoresizingMaskIntoConstraints = false\n  arrowLabel.widthAnchor.constraint(equalToConstant: 12).isActive = true\n  arrowLabel.topAnchor.constraint(equalTo: marginGuide.topAnchor).isActive = true\n  arrowLabel.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor).isActive = true\n  arrowLabel.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor).isActive = true\n\n  // Title label\n  contentView.addSubview(titleLabel)\n  titleLabel.textColor = UIColor.white\n  titleLabel.translatesAutoresizingMaskIntoConstraints = false\n  titleLabel.topAnchor.constraint(equalTo: marginGuide.topAnchor).isActive = true\n  titleLabel.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor).isActive = true\n  titleLabel.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor).isActive = true\n  titleLabel.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor).isActive = true\n}\n```\n\n#### Step 4. The UITableView DataSource and Delegate ####\n\nNow we implemented the header view, let's get back to the table view controller.\n\nThe number of sections is `sections.count`:\n\n```swift\noverride func numberOfSectionsInTableView(in tableView: UITableView) -\u003e Int {\n  return sections.count\n}\n```\n\nHere is the key ingredient of implementing the collapsible table section, if the section is collapsed, then that section should not have any row:\n\n```swift\noverride func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -\u003e Int {\n    return sections[section].collapsed ? 0 : sections[section].items.count\n}\n```\n\nNoticed that we don't need to render any cell for the collapsed section, this can improve the performance a lot if there are tons of cells in that section.\n\nNext, we use tableView's viewForHeaderInSection function to hook up our custom header:\n\n```swift\noverride func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -\u003e UIView? {\n    let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(\"header\") as? CollapsibleTableViewHeader ?? CollapsibleTableViewHeader(reuseIdentifier: \"header\")\n\n    header.titleLabel.text = sections[section].name\n    header.arrowLabel.text = \"\u003e\"\n    header.setCollapsed(sections[section].collapsed)\n\n    header.section = section\n    header.delegate = self\n\n    return header\n}\n```\n\nSetup the normal row cell is pretty straightforward:\n\n```swift\noverride func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -\u003e UITableViewCell {\n  let cell = tableView.dequeueReusableCell(withIdentifier: \"Cell\") as UITableViewCell? ?? UITableViewCell(style: .default, reuseIdentifier: \"Cell\")\n  cell.textLabel?.text = sections[indexPath.section].items[indexPath.row]\n  return cell\n}\n```\n\nIn the above code, we use the plain `UITableViewCell`, if you would like to see how to make a autosizing cell, please take a look at our `CollapsibleTableViewCell` in the source code. The `CollapsibleTableViewCell` is a subclass of `UITableViewCell` that adds the name and detail labels, and the most important thing is that it supports autosizing feature, the key is to setup the autolayout constrains properly, make sure the subviews are proplery stretched to the top and bottom in the `contentView`.\n\n#### Step 5. How to Toggle Collapse and Expand ####\n\nThe idea is pretty starightforward, reverse the `collapsed` flag for the section and tell the tableView to reload that section:\n\n```swift\nextension CollapsibleTableViewController: CollapsibleTableViewHeaderDelegate {\n  func toggleSection(_ header: CollapsibleTableViewHeader, section: Int) {\n    let collapsed = !sections[section].collapsed\n        \n    // Toggle collapse\n    sections[section].collapsed = collapsed\n    header.setCollapsed(collapsed)\n    \n    // Reload the whole section\n    tableView.reloadSections(NSIndexSet(index: section) as IndexSet, with: .automatic)\n  }\n}\n```\n\nAfter the sections get reloaded, the number of cells in that section will be recalculated and redrawn. \n\nThat's it, we have implemented the collapsible table section! Please refer to the source code and see the detailed implementation.\n\n## More Collapsible Demo ##\n\nSometimes you might want to implement the collapsible cells in a grouped-style table, I have a separate demo at [https://github.com/jeantimex/ios-swift-collapsible-table-section-in-grouped-section](https://github.com/jeantimex/ios-swift-collapsible-table-section-in-grouped-section). The implementation is pretty much the same but slightly different.\n\n## Can I use it as a pod? ##\n\n:tada: Yes! The CocoaPod is finally released, see [CollapsibleTableSectionViewController](https://github.com/jeantimex/CollapsibleTableSectionViewController).\n\n## Support ##\n\u003ca href=\"https://paypal.me/jeantimex/3\"\u003e\n  \u003cimg alt=\"But Me a Coffee\" src=\"https://az743702.vo.msecnd.net/cdn/kofi4.png?v=0\" width=\"200\" /\u003e\n\u003c/a\u003e\n\n## Contributors\n\nThis project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].\n\u003c!--\n\u003ca href=\"graphs/contributors\"\u003e\u003cimg src=\"https://opencollective.com/ios-collapsible-table-section/contributors.svg?width=890\" /\u003e\u003c/a\u003e\n--\u003e\n\n## Backers\n\nThank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/ios-collapsible-table-section#backer)]\n\n\u003ca href=\"https://opencollective.com/ios-collapsible-table-section#backers\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/ios-collapsible-table-section/backers.svg?width=890\"\u003e\u003c/a\u003e\n\n\n## Sponsors\n\nSupport this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/ios-collapsible-table-section#sponsor)]\n\u003c!--\n\u003ca href=\"https://opencollective.com/ios-collapsible-table-section/sponsor/0/website\" target=\"_blank\"\u003e\u003cimg src=\"https://opencollective.com/ios-collapsible-table-section/sponsor/0/avatar.svg\"\u003e\u003c/a\u003e\n--\u003e\n\n## License ##\n\nMIT License\n\nCopyright (c) 2019 Yong Su @jeantimex\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjeantimex%2Fios-swift-collapsible-table-section","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjeantimex%2Fios-swift-collapsible-table-section","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjeantimex%2Fios-swift-collapsible-table-section/lists"}