Skip to content

Instantly share code, notes, and snippets.

@ofl
Last active September 28, 2016 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ofl/dd005c1568681ff09423900354f075e8 to your computer and use it in GitHub Desktop.
Save ofl/dd005c1568681ff09423900354f075e8 to your computer and use it in GitHub Desktop.
ReactiveKit/Bond: Observable2DArray sample
//
// TableViewController.swift
//
// Created by Shin Morichika on 2016/09/28.
// Copyright © 2016年 covered. All rights reserved.
//
import UIKit
import Bond
class TableViewController: UITableViewController {
let viewModel = ViewModel.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
viewModel.array
.bind(to: tableView, using: MyBond())
.disposeIn(bnd_bag)
navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .add,
target: self,
action: #selector(addItem)
)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func addItem() {
viewModel.addItem()
}
}
class MyBond: TableViewBond {
typealias DataSource = Observable2DArray<SectionMetadata, City>
let viewModel = ViewModel.sharedInstance
func cellForRow(at indexPath: IndexPath, tableView: UITableView, dataSource: DataSource) -> UITableViewCell {
let city = viewModel.array[indexPath]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = city.name
return cell
}
func titleForHeader(in section: Int, dataSource: DataSource) -> String? {
return dataSource[section].metadata.header
}
}
// ViewModel.swift
//
// Created by Shin Morichika on 2016/09/28.
// Copyright © 2016年 covered. All rights reserved.
//
import Foundation
import Bond
typealias SectionMetadata = (header: String, footer: String)
struct City {
let name: String
}
struct ViewModel {
let array = MutableObservable2DArray(
[
Observable2DArraySection<SectionMetadata, City>(
metadata: (header: "Cities", footer: "That's it"),
items: [
City(name: "Paris"),
City(name: "Berlin"),
]
)
]
)
func addItem() {
array.appendItem(City(name: "Rome"), toSection: 0)
}
static var sharedInstance : ViewModel {
struct Static {
static let instance : ViewModel = ViewModel()
}
return Static.instance
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment