ActionSheetItemHandler.swift 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. //
  2. // ActionSheetItemHandler.swift
  3. // Sheeeeeeeeet
  4. //
  5. // Created by Daniel Saidi on 2017-11-24.
  6. // Copyright © 2017 Daniel Saidi. All rights reserved.
  7. //
  8. /*
  9. This class is used as data source and delegate for the item
  10. and button table views of the action sheet class.
  11. */
  12. import UIKit
  13. open class ActionSheetItemHandler: NSObject {
  14. // MARK: - Initialization
  15. public init(actionSheet: ActionSheet, itemType: ItemType) {
  16. self.actionSheet = actionSheet
  17. self.itemType = itemType
  18. }
  19. // MARK: - Enum
  20. public enum ItemType {
  21. case items, buttons
  22. }
  23. // MARK: - Properties
  24. private weak var actionSheet: ActionSheet?
  25. let itemType: ItemType
  26. var items: [ActionSheetItem] {
  27. switch itemType {
  28. case .buttons: return actionSheet?.buttons ?? []
  29. case .items: return actionSheet?.items ?? []
  30. }
  31. }
  32. }
  33. // MARK: - UITableViewDataSource
  34. extension ActionSheetItemHandler: UITableViewDataSource {
  35. public func item(at indexPath: IndexPath) -> ActionSheetItem? {
  36. guard indexPath.section == 0 else { return nil }
  37. guard items.count > indexPath.row else { return nil }
  38. return items[indexPath.row]
  39. }
  40. public func numberOfSections(in tableView: UITableView) -> Int {
  41. return 1
  42. }
  43. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  44. return items.count
  45. }
  46. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  47. guard let item = self.item(at: indexPath) else { return UITableViewCell(frame: .zero) }
  48. let cell = item.cell(for: tableView)
  49. item.applyAppearance(to: cell) // TODO: Deprecated - Remove in 1.4.0
  50. cell.refresh(with: item)
  51. return cell
  52. }
  53. public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  54. guard let item = self.item(at: indexPath) else { return 0 }
  55. return CGFloat(item.height)
  56. }
  57. }
  58. // MARK: - UITableViewDelegate
  59. extension ActionSheetItemHandler: UITableViewDelegate {
  60. public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  61. guard let item = self.item(at: indexPath) else { return }
  62. tableView.deselectRow(at: indexPath, animated: true)
  63. guard let sheet = actionSheet else { return }
  64. item.handleTap(in: sheet)
  65. sheet.handleTap(on: item)
  66. }
  67. }