// // CollectionViewCell.swift // VDS // // Created by Matt Bruce on 8/25/22. // import Foundation import UIKit import Combine open class CollectionViewCell: UICollectionViewCell, ModelHandlerable, ViewProtocol, Resettable { public typealias ModelType = ModelHandlerType.ModelType //-------------------------------------------------- // MARK: - Combine Properties //-------------------------------------------------- @Published public var model: ModelType = ModelType() public var modelPublisher: Published.Publisher { $model } public var subscribers = Set() //-------------------------------------------------- // MARK: - Properties //-------------------------------------------------- private var initialSetupPerformed = false public var modelHandler: ModelHandlerType = ModelHandlerType() @Proxy(\.model.surface) open var surface: Surface @Proxy(\.model.disabled) open var disabled: Bool { didSet { self.isEnabled = !disabled } } open var isEnabled: Bool { get { !model.disabled } set { //create local vars for clear coding let disabled = !newValue if model.disabled != disabled { model.disabled = disabled } } } //-------------------------------------------------- // MARK: - Initializers //-------------------------------------------------- required public init() { super.init(frame: .zero) initialSetup() } public required init(with model: ModelType) { super.init(frame: .zero) initialSetup() set(with: model) } public override init(frame: CGRect) { super.init(frame: frame) initialSetup() set(with: model) } public required init?(coder: NSCoder) { super.init(coder: coder) initialSetup() } //-------------------------------------------------- // MARK: - Setup //-------------------------------------------------- public func initialSetup() { if !initialSetupPerformed { initialSetupPerformed = true setupUpdateView() setup() } } //-------------------------------------------------- // MARK: - Overrides //-------------------------------------------------- open func shouldUpdateView(viewModel: ModelType) -> Bool { return modelHandler.shouldUpdateView(viewModel: viewModel) } open func updateView(viewModel: ModelType) { modelHandler.updateView(viewModel: viewModel) } open func reset() { backgroundColor = .clear if let model = model as? Resettable { model.reset() } } public func set(with model: ModelType) { self.model = model modelHandler.set(with: model) } // MARK: - ViewProtocol /// Will be called only once. open func setup() { translatesAutoresizingMaskIntoConstraints = false insetsLayoutMarginsFromSafeArea = false addSubview(modelHandler) modelHandler.topAnchor.constraint(equalTo: topAnchor).isActive = true modelHandler.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true modelHandler.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true modelHandler.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true } }