Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created March 23, 2015 14:20
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save chriseidhof/892c1a574d1f3975c697 to your computer and use it in GitHub Desktop.
Save chriseidhof/892c1a574d1f3975c697 to your computer and use it in GitHub Desktop.
//
// AppDelegate.swift
// TypedTableViewControllers
//
// Created by Chris Eidhof on 23/03/15.
// Copyright (c) 2015 Unsigned Integer. All rights reserved.
//
import UIKit
class Box<T> {
let unbox: T
init(_ value: T) { self.unbox = value }
}
class MyTableViewController: UITableViewController {
var items: [Any] = []
var configureCell: (UITableViewCell, Any) -> () = { _ in }
let identifier = "Identifier"
override func viewDidLoad() {
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: identifier)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(identifier) as! UITableViewCell
configureCell(cell, items[indexPath.row])
return cell
}
}
func exampleTableViewController<A>(items: [A], configure: (UITableViewCell, A) -> ()) -> UITableViewController {
var vc = MyTableViewController(style: UITableViewStyle.Plain)
vc.items = items.map { Box($0) }
vc.configureCell = { cell, obj in
if let value = obj as? Box<A> {
configure(cell, value.unbox)
}
}
return vc
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = exampleTableViewController([1,2,3]) { cell, num in
cell.textLabel?.text = "Cell \(num)"
}
window?.makeKeyAndVisible()
return true
}
}
@cfr
Copy link

cfr commented Mar 25, 2015

I wasn't able to use this controller with NIB. Here is updated version VC+tableView: https://gist.github.com/cfr/3326ef5d6a015d12fe46

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment