Created
March 23, 2015 14:20
-
-
Save chriseidhof/892c1a574d1f3975c697 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wasn't able to use this controller with NIB. Here is updated version VC+tableView: https://gist.github.com/cfr/3326ef5d6a015d12fe46