Skip to content

Instantly share code, notes, and snippets.

@blwinters
Created December 18, 2017 14:18
Show Gist options
  • Save blwinters/18e075ca898cc2befed1aa3df182ee2b to your computer and use it in GitHub Desktop.
Save blwinters/18e075ca898cc2befed1aa3df182ee2b to your computer and use it in GitHub Desktop.
A table view cell that displays a grid of days of the month by conforming to ButtonGridDisplayable.
//
// DaysOfMonthGridCell.swift
// Summit_iOS
//
// Created by Ben Winters on 9/25/17.
// Copyright © 2017 Goals LLC. All rights reserved.
//
import UIKit
protocol DaysOfMonthGridCellDelegate: class {
func didSelectDaysOfMonth(_ daysOfMonth: Set<Int>)
}
struct DaysOfMonthGridCellModel {
var selectedDays: [Int]
weak var delegate: DaysOfMonthGridCellDelegate!
}
class DaysOfMonthGridCell: UITableViewCell {
@IBOutlet weak var gridContainer: UIView!
@IBOutlet weak var hSeparatorContainerStack: UIStackView!
@IBOutlet weak var vSeparatorContainerStack: UIStackView!
@IBOutlet weak var buttonContainerStack: UIStackView!
private weak var delegate: DaysOfMonthGridCellDelegate!
let separatorThickness = Style.separatorHeight
let selectedColor = Style.primaryFillLight
let separatorColor = Style.cellSeparator
let buttonValues = Array(1...31)
let columnCount: Int = 7
var selectedValues: Set<Int> = [] {
didSet {
didSetSelectedValues()
}
}
static func newInstance(for tableView: UITableView, at indexPath: IndexPath, with cellModel: DaysOfMonthGridCellModel) -> DaysOfMonthGridCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: .daysOfMonthGrid, for: indexPath) as? DaysOfMonthGridCell else { return DaysOfMonthGridCell() }
cell.setup(with: cellModel)
return cell
}
override func awakeFromNib() {
super.awakeFromNib()
setupStackViews()
addSeparators()
}
func setup(with cellModel: DaysOfMonthGridCellModel) {
self.applyStandardFormatting()
self.delegate = cellModel.delegate
setupButtons()
self.selectedValues = Set(cellModel.selectedDays) //didSet configures the selected buttons
}
}
extension DaysOfMonthGridCell: ButtonGridDisplayable {
func titleForButtonValue(_ value: Int) -> String? {
return String(value)
}
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.didSelectDaysOfMonth(selectedValues)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment