Created
December 18, 2017 14:17
-
-
Save blwinters/29b8be7ff536d9919d44d1c5aa22f6d6 to your computer and use it in GitHub Desktop.
A table view cell that displays a grid of months by conforming to ButtonGridDisplayable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// MonthsOfYearGridCell.swift | |
// Summit_iOS | |
// | |
// Created by Ben Winters on 9/25/17. | |
// Copyright © 2017 Goals LLC. All rights reserved. | |
// | |
import UIKit | |
protocol MonthsOfYearGridCellDelegate: class { | |
func didSelectMonths(_ months: Set<Int>) | |
} | |
struct MonthsOfYearGridCellModel { | |
var selectedMonths: [Int] | |
weak var delegate: MonthsOfYearGridCellDelegate! | |
} | |
class MonthsOfYearGridCell: UITableViewCell { | |
//This keeps the width constrained and centered on larger devices | |
@IBOutlet weak var gridContainer: UIView! | |
//All 3 of the outer stack views are vertical | |
@IBOutlet weak var hSeparatorContainerStack: UIStackView! | |
@IBOutlet weak var vSeparatorContainerStack: UIStackView! | |
@IBOutlet weak var buttonContainerStack: UIStackView! | |
private weak var delegate: MonthsOfYearGridCellDelegate! | |
let separatorThickness = Style.separatorHeight | |
let selectedColor = Style.primaryFillLight | |
let separatorColor = Style.cellSeparator | |
let buttonValues = Array(1...12) | |
let columnCount = 4 | |
var selectedValues: Set<Int> = [] { | |
didSet { | |
didSetSelectedValues() | |
} | |
} | |
static func newInstance(for tableView: UITableView, at indexPath: IndexPath, with cellModel: MonthsOfYearGridCellModel) -> MonthsOfYearGridCell { | |
guard let cell = tableView.dequeueReusableCell(withIdentifier: .monthsOfYearGrid, for: indexPath) as? MonthsOfYearGridCell else { return MonthsOfYearGridCell() } | |
cell.setup(with: cellModel) | |
return cell | |
} | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
setupStackViews() | |
addSeparators() | |
} | |
func setup(with cellModel: MonthsOfYearGridCellModel) { | |
self.applyStandardFormatting() | |
self.delegate = cellModel.delegate | |
setupButtons() | |
self.selectedValues = Set(cellModel.selectedMonths) //didSet configures the selected buttons | |
} | |
} | |
extension MonthsOfYearGridCell: ButtonGridDisplayable { | |
@objc func didTapButton(sender: UIButton) { | |
let month = sender.tag | |
if selectedValues.contains(month), selectedValues.count != 1 { | |
selectedValues.remove(month) | |
} else { | |
selectedValues.insert(month) | |
} | |
//didSet will change button.isSelected appropriately | |
delegate.didSelectMonths(selectedValues) | |
} | |
func titleForButtonValue(_ value: Int) -> String? { | |
return Date.mmmDescription(for: value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment