Last active
July 6, 2018 05:57
-
-
Save yashthaker7/4aafe5881a31db9e4547a50fa67c5218 to your computer and use it in GitHub Desktop.
Generic TableView Controller
This file contains hidden or 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
// GenericTableViewController.swift | |
// Generics | |
// | |
// Created by Yash Thaker on 01/07/18. | |
// Copyright © 2018 YashThaker. All rights reserved. | |
import UIKit | |
/* | |
// <---------- HERE IS HOW TO USE. ----------> | |
struct User { | |
let name, email: String | |
} | |
class UserCell: GenericCell<User> { | |
override var item: User! { | |
didSet { | |
textLabel?.text = "\(item.name):- \(item.email)" | |
} | |
} | |
} | |
class ViewController: GenericTableViewController<UserCell, User> { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
items = [User(name: "Yash", email: "[email protected]"), | |
User(name: "Sunny", email: "[email protected]")] | |
} | |
} | |
*/ | |
class GenericTableViewController<T: GenericCell<U>, U>: UITableViewController { | |
var items = [U]() | |
let cellId = "cellId" | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
tableView.register(T.self, forCellReuseIdentifier: cellId) | |
} | |
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return items.count | |
} | |
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as! T | |
cell.item = items[indexPath.row] | |
return cell | |
} | |
} | |
class GenericCell<U>: UITableViewCell { | |
var item: U! | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment