🍣
【Swift】《Constantsファイル版》カスタムセルのコード【コピペコード】
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.register(UINib(nibName: K.cellNibName, bundle: nil), forCellReuseIdentifier: K.cellIdentifier)
}
extension ChatViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let message = messages[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: K.cellIdentifier, for: indexPath) as! MessageCell
cell.label.text = message.body
return cell
}
}
「messages」は「変数名」
【「Constants.swift ファイル」の中身】
struct K {
static let cellIdentifier = "ReusableCell"
static let cellNibName = "MessageCell"
}
参考教材・記事
iOS & Swift - The Complete iOS App Development Bootcamp
190. Customising Cells in a TableView using a .xib File
UICollectionViewのカスタムセルの作り方とセルの再利用について
Discussion