// // SortController.swift // CapCollector // // Created by Christoph on 12.11.18. // Copyright © 2018 CH. All rights reserved. // import UIKit enum SortCriteria: Int { case id = 0 case name = 1 case count = 2 case match = 3 } protocol SortControllerDelegate: class { var sortControllerShouldIncludeMatchOption: Bool { get } func sortController(didSelect sortType: SortCriteria, ascending: Bool) } class SortController: UITableViewController { var selected: SortCriteria = .count var ascending: Bool = true private var includeMatches: Bool { delegate?.sortControllerShouldIncludeMatchOption ?? false } weak var delegate: SortControllerDelegate? override func viewDidLoad() { super.viewDidLoad() let height = includeMatches ? 298 : 258 preferredContentSize = CGSize(width: 200, height: height) } private func giveFeedback(_ style: UIImpactFeedbackGenerator.FeedbackStyle) { let generator = UIImpactFeedbackGenerator(style: style) generator.impactOccurred() } // MARK: - Table view data source override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard indexPath.section == 1 else { ascending = !ascending tableView.reloadData() delegate?.sortController(didSelect: selected, ascending: ascending) giveFeedback(.light) return } giveFeedback(.medium) selected = SortCriteria(rawValue: indexPath.row)! delegate?.sortController(didSelect: selected, ascending: ascending) self.dismiss(animated: true) } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { guard indexPath.row == 3 else { return indexPath } return includeMatches ? indexPath : nil } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { switch indexPath.section { case 0: cell.accessoryType = ascending ? .checkmark : .none default: cell.accessoryType = indexPath.row == selected.rawValue ? .checkmark : .none break } } }