Skip to content

Instantly share code, notes, and snippets.

@kfurue
Created May 29, 2018 01:32
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 kfurue/c843ab9acb74d652f7501c8112f5c3dc to your computer and use it in GitHub Desktop.
Save kfurue/c843ab9acb74d652f7501c8112f5c3dc to your computer and use it in GitHub Desktop.
SwiftでGenericsを使ったTableViewの実装 ref: https://qiita.com/kfurue/items/caf4e866891b9b8a7bdc
import Foundation
import UIKit
protocol Nibable: NSObjectProtocol {
static var nibName: String { get }
static var nib: UINib { get }
}
extension Nibable {
static var nibName: String {
return String(describing: self)
}
static var nib: UINib {
return UINib(nibName: nibName, bundle: Bundle(for: self))
}
}
import Foundation
import UIKit
extension UITableView {
func register<T: UITableViewCell>(_ cellType: T.Type) where T: Nibable {
register(T.nib, forCellReuseIdentifier: T.identifier)
}
func register<T: UITableViewCell>(_ cellType: T.Type) {
register(T.self, forCellReuseIdentifier: T.identifier)
}
func dequeueReusableCell<T: UITableViewCell>(with cellType: T.Type,
for indexPath: IndexPath) -> T {
// swiftlint:disable force_cast
return dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as! T
// swiftlint:enable force_cast
}
}
import Foundation
import UIKit
extension UITableViewCell {
static var identifier: String {
return String(describing: self)
}
}
import UIKit
class MicropostTableViewCell: UITableViewCell, Nibable {
func configure(micropost: Micropost) {
textLabel?.text? = micropost.content
detailTextLabel?.text? = String(micropost.userId)
}
}
viewModel.feeds.asDriver().drive(
feedTableView.rx.items(cellIdentifier: MicropostTableViewCell.identifier,
cellType: MicropostTableViewCell.self),
curriedArgument: { row, micropost, cell in
cell.configure(micropost: micropost)
}).disposed(by: disposeBag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment