Skip to content

Instantly share code, notes, and snippets.

@hmhmsh
Created January 30, 2020 06:56
Show Gist options
  • Save hmhmsh/e7b8ba53712970d1117950b89c097d81 to your computer and use it in GitHub Desktop.
Save hmhmsh/e7b8ba53712970d1117950b89c097d81 to your computer and use it in GitHub Desktop.
UITableViewCellで自作enumを使う
extension UITableView {
func dequeueReusableCell<ROW: Identifiable>(with row: ROW, for indexPath: IndexPath) -> UITableViewCell where ROW.ID == String {
return self.dequeueReusableCell(withIdentifier: row.id, for: indexPath)
}
}
class APresenter {
enum Row: Identifiable {
case title(String)
case body(String)
case icon(UIImage)
enum Identifier: String {
case MyTextCell
case MyImageCell
}
typealias ID = String
var id: Self.ID {
switch self {
case .title, .body:
return Identifier.MyTextCell.rawValue
case .icon:
return Identifier.MyImageCell.rawValue
}
}
}
func row(cellForRowAt indexPath: IndexPath) -> Row {
switch indexPath.row {
case 1:
return .body("本文")
case 2:
return .icon(UIImage(imageLiteralResourceName: "myIcon.jpg"))
default:
return .title("タイトル")
}
}
}
class AViewController: UIViewController, UITableViewDataSource {
lazy var presenter = APresenter()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = presenter.row(cellForRowAt: indexPath)
let cell = tableView.dequeueReusableCell(with: row, for: indexPath)
switch row {
case .title(let title):
cell.textLabel?.text = title
case .body(let body):
cell.textLabel?.text = body
case .icon(let icon):
cell.imageView?.image = icon
}
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment