今回の内容
-
UITableViewCell
の再利用について調べた時に作成したサンプルアプリがあったので、簡単な解説とコードです。
サンプルアプリ

-
再利用された
UITableViewCell
は背景色を.systemGreen
にして、cell.detailTextLabel.text
に再利用される直前にcell.textLabel.text
に表示していた値を、表示してどのcell
がどこに再利用されたかを見ることが出来ます。 -
required init?(coder: NSCoder){ super.init(coder: coder) }
はCellのインスタンスを生成するタイミングで処理が働きます。 -
prepareForReuse()
はUITableView
が持っているReuseQueue
からCell
を再利用するタイミングで処理が働きます。(まだtableViewにCellが表示される訳では無いです) -
tableView
にCell
が表示されるタイミングで処理が働くのが、func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}
です。 -
全てコードで書いています。コピペだけで試せますので宜しければご覧ください。
import UIKit
class ViewController: UIViewController {
let tableView = UITableView()
var count = Int()
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = CGRect(x: view.frame.minX, y: view.frame.minY, width: view.frame.width, height: view.frame.height)
tableView.register(CustomCell.self, forCellReuseIdentifier: "cell")
view.addSubview(tableView)
tableView.dataSource = self
}
}
extension ViewController:UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
count = count + 1
print(count)
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
if cell.textLabel?.text != ""{
cell.detailTextLabel?.text = cell.textLabel?.text
}
cell.textLabel?.text = String(indexPath.row)
return cell
}
}
class CustomCell:UITableViewCell{
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func prepareForReuse() {
super.prepareForReuse()
if textLabel?.text != ""{
detailTextLabel?.text = ""
detailTextLabel?.text = textLabel!.text
}
backgroundColor = .systemGreen
print("reuse")
}
}
終わり
ご指摘、ご質問などありましたら、コメントまでお願い致します。