Created
February 6, 2019 18:09
-
-
Save pawelkijowskizimperium/fe1e8511a7932a0d40486a2669316d2c to your computer and use it in GitHub Desktop.
TableView With Dynamic Sections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// TableViewWithDynamicSections | |
// | |
// Created by Pawel Kijowski on 2/6/19. | |
// Copyright © 2019 Pawel Kijowski. All rights reserved. | |
// | |
import UIKit | |
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { | |
@IBOutlet var tableView: UITableView! | |
var headerButtons: [UIButton]! | |
var sections = [true, true, true] | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
tableView.dataSource = self | |
tableView.delegate = self | |
let section0Button = UIButton(type: .detailDisclosure) | |
section0Button.setTitle("Section 0", for: .normal) | |
section0Button.addTarget(self, action: #selector(section0Tapped), for: .touchUpInside) | |
let section1Button = UIButton(type: .detailDisclosure) | |
section1Button.setTitle("Section 1", for: .normal) | |
section1Button.addTarget(self, action: #selector(section1Tapped), for: .touchUpInside) | |
let section2Button = UIButton(type: .detailDisclosure) | |
section2Button.setTitle("Section 2", for: .normal) | |
section2Button.addTarget(self, action: #selector(section2Tapped), for: .touchUpInside) | |
headerButtons = [UIButton]() | |
headerButtons.append(section0Button) | |
headerButtons.append(section1Button) | |
headerButtons.append(section2Button) | |
} | |
func numberOfSections(in tableView: UITableView) -> Int { | |
return sections.count | |
} | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return sections[section] ? 3 : 0 | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cellReuseId = "cellReuseId" | |
let cell = UITableViewCell(style: .default, reuseIdentifier: cellReuseId) | |
cell.textLabel?.text = "\(indexPath.section): \(indexPath.row)" | |
return cell | |
} | |
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { | |
return headerButtons[section] | |
} | |
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { | |
return 44 | |
} | |
@objc func section0Tapped() { | |
sections[0] = !sections[0] | |
tableView.reloadSections([0], with: .fade) | |
} | |
@objc func section1Tapped() { | |
sections[1] = !sections[1] | |
tableView.reloadSections([1], with: .fade) | |
} | |
@objc func section2Tapped() { | |
sections[2] = !sections[2] | |
tableView.reloadSections([2], with: .fade) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment