Created
January 30, 2020 06:56
-
-
Save hmhmsh/e7b8ba53712970d1117950b89c097d81 to your computer and use it in GitHub Desktop.
UITableViewCellで自作enumを使う
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
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) | |
} | |
} |
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
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("タイトル") | |
} | |
} | |
} |
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
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