RadioSelectionTableViewController.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // RadioSelectionTableViewController.swift
  3. // Loop
  4. //
  5. // Created by Nate Racklyeft on 8/26/16.
  6. // Copyright © 2016 Nathan Racklyeft. All rights reserved.
  7. //
  8. import UIKit
  9. public protocol RadioSelectionTableViewControllerDelegate: AnyObject {
  10. func radioSelectionTableViewControllerDidChangeSelectedIndex(_ controller: RadioSelectionTableViewController)
  11. }
  12. open class RadioSelectionTableViewController: UITableViewController {
  13. open var options = [String]()
  14. open var selectedIndex: Int? {
  15. didSet {
  16. if let oldValue = oldValue, oldValue != selectedIndex {
  17. tableView.cellForRow(at: IndexPath(row: oldValue, section: 0))?.accessoryType = .none
  18. }
  19. if let selectedIndex = selectedIndex, oldValue != selectedIndex {
  20. tableView.cellForRow(at: IndexPath(row: selectedIndex, section: 0))?.accessoryType = .checkmark
  21. delegate?.radioSelectionTableViewControllerDidChangeSelectedIndex(self)
  22. }
  23. }
  24. }
  25. open var contextHelp: String?
  26. weak open var delegate: RadioSelectionTableViewControllerDelegate?
  27. convenience public init() {
  28. self.init(style: .grouped)
  29. }
  30. // MARK: - Table view data source
  31. override open func numberOfSections(in tableView: UITableView) -> Int {
  32. return 1
  33. }
  34. override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  35. return options.count
  36. }
  37. override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  38. let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell(style: .default, reuseIdentifier: "Cell")
  39. cell.textLabel?.text = options[indexPath.row]
  40. cell.accessoryType = selectedIndex == indexPath.row ? .checkmark : .none
  41. return cell
  42. }
  43. override open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
  44. return contextHelp
  45. }
  46. override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  47. selectedIndex = indexPath.row
  48. tableView.deselectRow(at: indexPath, animated: true)
  49. }
  50. }