ActionSheetItemHandler.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. import UIKit
  9. open class ActionSheetItemHandler: NSObject {
  10. // MARK: - Initialization
  11. init(actionSheet: ActionSheet, handles itemType: ItemType) {
  12. self.actionSheet = actionSheet
  13. self.itemType = itemType
  14. }
  15. // MARK: - Enum
  16. public enum ItemType {
  17. case items, buttons
  18. }
  19. // MARK: - Properties
  20. private weak var actionSheet: ActionSheet?
  21. private var itemType: ItemType
  22. private var items: [ActionSheetItem] {
  23. switch itemType {
  24. case .buttons: return actionSheet?.buttons ?? []
  25. case .items: return actionSheet?.items ?? []
  26. }
  27. }
  28. }
  29. // MARK: - UITableViewDataSource
  30. extension ActionSheetItemHandler: UITableViewDataSource {
  31. public func item(at indexPath: IndexPath) -> ActionSheetItem {
  32. return items[indexPath.row]
  33. }
  34. public func numberOfSections(in tableView: UITableView) -> Int {
  35. return 1
  36. }
  37. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  38. return items.count
  39. }
  40. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  41. return item(at: indexPath).cell(for: tableView)
  42. }
  43. public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  44. return CGFloat(item(at: indexPath).appearance.height)
  45. }
  46. }
  47. // MARK: - UITableViewDelegate
  48. extension ActionSheetItemHandler: UITableViewDelegate {
  49. public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  50. guard items.count > indexPath.row else { return }
  51. let item = self.item(at: indexPath)
  52. let cell = tableView.cellForRow(at: indexPath)
  53. tableView.deselectRow(at: indexPath, animated: true)
  54. guard let sheet = actionSheet else { return }
  55. item.handleTap(in: sheet, cell: cell)
  56. sheet.itemTapAction(item)
  57. }
  58. }