From f1f86ced290ed1823a5a48135b367c77a54772e9 Mon Sep 17 00:00:00 2001 From: James Magahern Date: Fri, 13 Mar 2020 19:36:44 -0700 Subject: [PATCH] SwitchesViewController: Modernize switches collection view controller This switches to using the more modern collection view diffable data source API. Also I moved the action cells into their own section so we don't need to do arithmetic to determine whether or not a cell is an action cell or a device cell. --- .../Controllers/SwitchesViewController.swift | 175 ++++++++---------- XIONControlPanel/Servers/ServerProtocol.swift | 9 + .../{Controllers => Servers}/WemoServer.swift | 0 3 files changed, 82 insertions(+), 102 deletions(-) create mode 100644 XIONControlPanel/Servers/ServerProtocol.swift rename XIONControlPanel/{Controllers => Servers}/WemoServer.swift (100%) diff --git a/XIONControlPanel/Controllers/SwitchesViewController.swift b/XIONControlPanel/Controllers/SwitchesViewController.swift index cd787aa..663205a 100644 --- a/XIONControlPanel/Controllers/SwitchesViewController.swift +++ b/XIONControlPanel/Controllers/SwitchesViewController.swift @@ -21,20 +21,25 @@ extension SwitchesViewControllerDelegate } class SwitchesViewController: UIViewController, - UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { - weak var delegate: SwitchesViewControllerDelegate? + weak var delegate: SwitchesViewControllerDelegate? - fileprivate var _collectionView: UICollectionView = UICollectionView(frame: CGRect.zero, - collectionViewLayout: UICollectionViewFlowLayout()) - fileprivate var _currentDevicesHash: Int = 0 + fileprivate var _collectionView: UICollectionView = UICollectionView(frame: CGRect.zero, + collectionViewLayout: UICollectionViewFlowLayout()) + + fileprivate var _collectionViewDataSource: UICollectionViewDiffableDataSource! + + fileprivate var _currentDevicesHash: Int = 0 static fileprivate let collectionViewDeviceSwitchCellReuseIdentifier = "DeviceSwitchReuseID" static fileprivate let collectionViewActionCellReuseIdentifier = "ActionCellReuseID" static fileprivate let collectionViewCellsSpacing: CGFloat = 5.0 - fileprivate enum ActionCell: Int + static fileprivate let actionCellsSectionIdentifier = 0 + static fileprivate let switchCellsSectionIdentifier = 1 + + fileprivate enum ActionCell: Int, CaseIterable { case allOn case allOff @@ -49,13 +54,37 @@ class SwitchesViewController: UIViewController, } } - static let count: Int = { - var max = 0 - while let _ = ActionCell(rawValue: max) { max += 1 } - return max - }() + static let count: Int = { return ActionCell.allCases.count }() } + override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) + { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + + _collectionViewDataSource = UICollectionViewDiffableDataSource(collectionView: _collectionView, cellProvider: { (collectionView, indexPath, identifier) -> UICollectionViewCell? in + return self.collectionView(collectionView, cellForItemAt: indexPath, identifier: identifier) + }) + + // Initialize data source + var snapshot = _collectionViewDataSource.snapshot() + + // Sections + snapshot.appendSections([ + SwitchesViewController.actionCellsSectionIdentifier, + SwitchesViewController.switchCellsSectionIdentifier, + ]) + + // Action cells + snapshot.appendItems([ + SwitchesViewController.ActionCell.allOn.rawValue, + SwitchesViewController.ActionCell.allOff.rawValue + ], toSection: SwitchesViewController.actionCellsSectionIdentifier) + + _collectionViewDataSource.apply(snapshot, animatingDifferences: false) + } + + required init?(coder: NSCoder) { fatalError("Unimplemented") } + override func viewDidLoad() { super.viewDidLoad() @@ -69,7 +98,7 @@ class SwitchesViewController: UIViewController, _collectionView.backgroundColor = UIColor.black _collectionView.delegate = self - _collectionView.dataSource = self + _collectionView.dataSource = _collectionViewDataSource _collectionView.register(WemoDeviceCellView.self, forCellWithReuseIdentifier: deviceCellReuseID) _collectionView.register(WemoActionCellView.self, forCellWithReuseIdentifier: actionCellReuseID) self.view.addSubview(_collectionView) @@ -97,87 +126,37 @@ class SwitchesViewController: UIViewController, return (d1.name.compare(d2.name, options: .caseInsensitive, range: nil, locale: nil) == .orderedAscending) }) - let hash = self.devices.reduce(0, {$0 ^ $1.hashValue}) - if (hash != _currentDevicesHash) { - let previousSet = NSOrderedSet(array: oldValue) - let newSet = NSOrderedSet(array: self.devices) - var insertedIndexPaths: [IndexPath] = [] - var updatedIndexPaths: [IndexPath] = [] - var deletedIndexPaths: [IndexPath] = [] - - // if we have devices now and we didn't before, or vice versa, - // we need to update the action cells - if ((oldValue.count == 0 && self.devices.count != 0) || (self.devices.count == 0 && oldValue.count != 0)) { - for actionCellIdx in 0 ..< ActionCell.count { - let actionCellIndexPath = IndexPath(item: actionCellIdx, section: 0) - updatedIndexPaths.append(actionCellIndexPath) - } - } - - // find deletes and updates - for (idx, device) in previousSet.enumerated() { - let itemIndex = idx + ActionCell.count - let curIndexPath = IndexPath(item: itemIndex, section: 0) - - if (!newSet.contains(device)) { - deletedIndexPaths.append(curIndexPath) - } else if (idx < newSet.count) { - let deviceInNewSet = newSet.object(at: idx) as! WemoDevice - if (deviceInNewSet != (device as! WemoDevice)) { - updatedIndexPaths.append(curIndexPath) - } - } - } - - // find insertions - for (idx, device) in newSet.enumerated() { - if (!previousSet.contains(device)) { - let itemIndex = idx + ActionCell.count - let insertedIndexPath = IndexPath(item: itemIndex, section: 0) - insertedIndexPaths.append(insertedIndexPath) - } - } - - UIView.performWithoutAnimation { () -> Void in - self._collectionView.performBatchUpdates({ () -> Void in - self._collectionView.deleteItems(at: deletedIndexPaths) - self._collectionView.reloadItems(at: updatedIndexPaths) - self._collectionView.insertItems(at: insertedIndexPaths) - }, completion: nil) - } - - _currentDevicesHash = hash - } + var snapshot = _collectionViewDataSource.snapshot() + snapshot.appendItems(self.devices.map { $0.hashValue }, toSection: SwitchesViewController.switchCellsSectionIdentifier) + _collectionViewDataSource.apply(snapshot, animatingDifferences: false) } } // MARK: UICollectionView - func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath, identifier: Int) -> UICollectionViewCell? { - return self.devices.count + ActionCell.count - } - - func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell - { - if (indexPath.item < ActionCell.count) { + if (indexPath.section == SwitchesViewController.actionCellsSectionIdentifier) { let reuseID = SwitchesViewController.collectionViewActionCellReuseIdentifier let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseID, for: indexPath) as! WemoActionCellView - cell.textLabel.text = ActionCell(rawValue: indexPath.item)?.name().uppercased() + cell.textLabel.text = ActionCell(rawValue: identifier)?.name().uppercased() cell.enabled = (self.devices.count > 0) return cell - } else { + } else if (indexPath.section == SwitchesViewController.switchCellsSectionIdentifier) { let reuseID = SwitchesViewController.collectionViewDeviceSwitchCellReuseIdentifier let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseID, for: indexPath) as! WemoDeviceCellView - let device = _deviceAtIndexPath(indexPath) - cell.deviceName = device.name - cell.toggled = (device.state == .on) - cell.ordinal = indexPath.item - ActionCell.count + 1 + if let device = (self.devices.first { $0.hashValue == identifier }) { + cell.deviceName = device.name + cell.toggled = (device.state == .on) + cell.ordinal = indexPath.row + } return cell } + + return nil } func collectionView(_ collectionView: UICollectionView, @@ -206,28 +185,33 @@ class SwitchesViewController: UIViewController, } let dimensions = floor((collectionView.bounds.size.width / cellsPerRow) - ((spacing * (cellsPerRow - 1.0)) / cellsPerRow)) - if (indexPath.item < ActionCell.count) { + if (indexPath.section == SwitchesViewController.actionCellsSectionIdentifier) { return CGSize(width: collectionView.bounds.size.width, height: rint(dimensions / 1.5)) } else { return CGSize(width: dimensions, height: dimensions) } } + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets + { + let spacing = SwitchesViewController.collectionViewCellsSpacing + return UIEdgeInsets(top: spacing, left: 0, bottom: 0, right: 0) + } + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { - if (indexPath.item < ActionCell.count) { + if (indexPath.section == SwitchesViewController.actionCellsSectionIdentifier) { let tappedActionCell = ActionCell(rawValue: indexPath.item) - var currentDelay: TimeInterval = 0.0 - for i in ActionCell.count ..< collectionView.numberOfItems(inSection: indexPath.section) { - if let cell = collectionView.cellForItem(at: IndexPath(item: i, section: indexPath.section)) as? WemoDeviceCellView { + for cell in collectionView.visibleCells { + if collectionView.indexPath(for: cell)?.section == SwitchesViewController.switchCellsSectionIdentifier { + let switchCell = cell as! WemoDeviceCellView let animOptions = UIView.AnimationOptions([.allowUserInteraction]) - UIView.animate(withDuration: 0.3, delay: currentDelay, options: animOptions, animations: { - cell.toggled = (tappedActionCell == .allOn) + let delay: TimeInterval = Double(switchCell.ordinal) * 0.05 + UIView.animate(withDuration: 0.3, delay: delay, options: animOptions, animations: { + switchCell.toggled = (tappedActionCell == .allOn) }, completion: nil) - - currentDelay += 0.05 } } @@ -236,11 +220,11 @@ class SwitchesViewController: UIViewController, } self.delegate?.switchesViewControllerDidToggleDevices(self, devices: self.devices) - } else { + } else if (indexPath.section == SwitchesViewController.switchCellsSectionIdentifier) { let cell = collectionView.cellForItem(at: indexPath) as! WemoDeviceCellView cell.toggled = !cell.toggled - let device = _deviceAtIndexPath(indexPath) + let device = self.devices[indexPath.row] device.state = (cell.toggled ? .on : .off) self.delegate?.switchesViewControllerDidToggleDevices(self, devices: [device]) @@ -249,28 +233,15 @@ class SwitchesViewController: UIViewController, func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { - if (indexPath.item < ActionCell.count) { - return (self.devices.count > 0) - } else { - return true - } + return self.collectionView(collectionView, shouldSelectItemAt: indexPath) } func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { - if (indexPath.item < ActionCell.count) { + if (indexPath.section == SwitchesViewController.actionCellsSectionIdentifier) { return (self.devices.count > 0) } else { return true } } - - // MARK: Internal - - internal func _deviceAtIndexPath(_ indexPath: IndexPath) -> WemoDevice - { - let deviceIdx = indexPath.item - ActionCell.count - let device = self.devices[deviceIdx] - return device - } } diff --git a/XIONControlPanel/Servers/ServerProtocol.swift b/XIONControlPanel/Servers/ServerProtocol.swift new file mode 100644 index 0000000..fed384a --- /dev/null +++ b/XIONControlPanel/Servers/ServerProtocol.swift @@ -0,0 +1,9 @@ +// +// ServerProtocol.swift +// XIONControlPanel +// +// Created by James Magahern on 3/13/20. +// Copyright © 2020 XION. All rights reserved. +// + +import Foundation diff --git a/XIONControlPanel/Controllers/WemoServer.swift b/XIONControlPanel/Servers/WemoServer.swift similarity index 100% rename from XIONControlPanel/Controllers/WemoServer.swift rename to XIONControlPanel/Servers/WemoServer.swift