xibを使用してTableViewCellにただ表示させるコード
CellModelに追加する想定で、仮のダミーを用意してCellに表示する。
Controller
TableViewController.swift
import UIKit
final class TableViewController: UIViewController {
private let CELL_NIB_NAME = "TableViewCell"
private let CELL_ID = "TableViewCell"
var dummyModel:[CellModel]{
[
CellModel.init(number: "1", menu: "hoge"),
CellModel.init(number: "1", menu: "hoge"),
CellModel.init(number: "1", menu: "hoge"),
CellModel.init(number: "1", menu: "hoge"),
CellModel.init(number: "1", menu: "hoge"),
CellModel.init(number: "1", menu: "hoge"),
CellModel.init(number: "1", menu: "hoge"),
CellModel.init(number: "1", menu: "hoge"),
CellModel.init(number: "1", menu: "hoge"),
CellModel.init(number: "1", menu: "hoge"),
]
}
@IBOutlet private weak var tableView: UITableView! {
didSet {
let cellNIB = UINib(nibName: CELL_NIB_NAME, bundle: nil)
tableView.register(cellNIB, forCellReuseIdentifier: CELL_ID)
tableView.delegate = self
tableView.dataSource = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension TableViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dummyModel.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID, for: indexPath) as? TableViewCell else {
return UITableViewCell()
}
let user = dummyModel[indexPath.row]
cell.configure(contents: user)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
}
extension TableViewController: UITableViewDelegate {
}
View
TableViewCell.swift
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet private weak var pctureImage: UIImageView!
@IBOutlet private weak var numberName: UILabel!
@IBOutlet private weak var menuName: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
pctureImage.image = nil
numberName.text = nil
menuName.text = nil
}
func configure(contents: CellModel) {
menuName.text = contents.menu
numberName.text = contents.number
}
}
Model
CellModel.swift
import Foundation
struct CellModel {
var number: String
var menu: String
}