Skip to content

Instantly share code, notes, and snippets.

@crenwick
Created November 18, 2015 19:57
Show Gist options
  • Save crenwick/5308aad302783c938fa9 to your computer and use it in GitHub Desktop.
Save crenwick/5308aad302783c938fa9 to your computer and use it in GitHub Desktop.
MVVM-ProtocolOriented
import UIKit
///////////////
// View Cell //
///////////////
protocol SwitchWithTextCellDataSource {
var title: String { get }
var switchOn: Bool { get }
}
protocol SwitchWithTextCellDelegate {
func onSwitchToggleOn(on: Bool)
var switchColor: UIColor { get }
var textColor: UIColor { get }
var font: UIFont { get }
}
extension SwitchWithTextCellDelegate {
var switchColor: UIColor { return .purpleColor() }
var textColor: UIColor { return .blackColor() }
var font: UIFont { return .systemFontOfSize(17) }
}
class SwitchWithTextTableViewCell: UITableViewCell {
@IBOutlet private weak var label: UILabel!
@IBOutlet private var switchToggle: UISwitch!
private var dataSource: SwitchWithTextCellDataSource?
private var delegate: SwitchWithTextCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
func configure(withDataSource dataSource: SwitchWithTextCellDataSource, delegate: SwitchWithTextCellDelegate?) {
self.dataSource = dataSource
self.delegate = delegate
label.text = dataSource.title
switchToggle.on = dataSource.switchOn
switchToggle.onTintColor = delegate?.switchColor
}
@IBAction func onSwitchToggle(sender: UISwitch) {
delegate?.onSwitchToggleOn(sender.on)
}
}
////////////////
// View Model //
////////////////
struct MinionModelViewModel: SwitchWithTextCellDataSource {
var title = "Minion Mode!!!"
var switchOn = true
}
extension MinionModelViewModel: SwitchWithTextCellDelegate {
func onSwitchToggleOn(on: Bool) {
if on {
print("minions are here")
} else { print("minions are out") }
}
var switchColor: UIColor { return .yellowColor() }
}
/////////////////////
// View Controller //
/////////////////////
class SettingsViewController: UITableViewController {
enum Setting: Int { case MinionMode }
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let setting = Setting(rawValue: indexPath.row) {
switch setting {
case .MinionMode:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchWithTextTableviewCell", forIndexPath: indexPath) as! SwitchWithTextTableViewCell
let viewModel = MinionModelViewModel()
cell.configure(withDataSource: viewModel, delegate: viewModel)
return cell
}
}
return tableView.dequeueReusableCellWithIdentifier("defaultCell", forIndexPath: indexPath)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment