🍣

【Swift】《Constantsファイル版》カスタムセルのコード【コピペコード】

2023/06/07に公開
@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
https://www.udemy.com/course/ios-13-app-development-bootcamp/

UICollectionViewのカスタムセルの作り方とセルの再利用について
https://qiita.com/takehilo/items/1145240bb3b72f7d0317

Discussion