Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// 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

This comment has been minimized.

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