// // TabsTableViewController.swift // Tusker // // Created by Shadowfacts on 10/5/18. // Copyright © 2018 Shadowfacts. All rights reserved. // import UIKit class TabsTableViewController: UITableViewController { var tabs: [(Tab, Bool)] = [] override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib(nibName: "TabTableViewCell", bundle: nil), forCellReuseIdentifier: "tabCell") tabs = Preferences.shared.tabs.filter { $0.value >= 0 }.sorted(by: { $0.value < $1.value }).map { ($0.key, true) } tabs.append(contentsOf: Preferences.shared.tabs.filter { $0.value == -1 }.map { ($0.key, false) }) tableView.setEditing(true, animated: false) } func updatePreferences() { var dict = [Tab: Int]() var maxIndex = 0 for (tab, enabled) in tabs { if enabled { dict[tab] = maxIndex maxIndex += 1 } else { dict[tab] = -1 } } Preferences.shared.tabs = dict guard let tabBarController = tabBarController as? MainTabBarViewController else { fatalError("Tab bar controller should be of type MainTabBarViewController") } tabBarController.updateTabs(animated: true) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tabs.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "tabCell", for: indexPath) as? TabTableViewCell else { fatalError() } let (tab, _) = tabs[indexPath.row] cell.updateUI(for: tab) cell.delegate = self return cell } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .none } override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let tab = tabs.remove(at: sourceIndexPath.row) tabs.insert(tab, at: destinationIndexPath.row) updatePreferences() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension TabsTableViewController: TabTableViewCellDelegate { func setEnabled(tab: Tab, enabled: Bool) { let index = tabs.firstIndex(where: { $0.0 == tab })! tabs[index] = (tab, enabled) updatePreferences() } }