Skip to content

Commit

Permalink
Demonstrate a bug in willDisplay cell
Browse files Browse the repository at this point in the history
  • Loading branch information
toshi0383 committed Oct 22, 2021
1 parent 5dacb00 commit 88da462
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ struct MessageModel {
let imageName: String
let message: String
let time: String

}

extension MessageModel {

init() {
imageName = Const.imageNames[Int(arc4random_uniform(UInt32(Const.imageNames.count)))]
message = Const.messags[Int(arc4random_uniform(UInt32(Const.messags.count)))]
Expand Down
29 changes: 25 additions & 4 deletions ReverseExtensionSample/ReverseExtensionSample/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ class ViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!

fileprivate var messages: [MessageModel] = []
private var sections: [[MessageModel]] = (1...10)
.map { i -> [MessageModel] in
(0..<i)
.map {
MessageModel(imageName: "marty1", message: "\($0) hello", time: "00:00")
}
}

override func viewDidLoad() {
super.viewDidLoad()
Expand All @@ -39,28 +45,43 @@ class ViewController: UIViewController {
}

@IBAction func addButtonTapped(_ sender: UIBarButtonItem) {
let i = sections.count - 1
var messages = sections[i]
messages.append(MessageModel())
sections[i] = messages
tableView.beginUpdates()
tableView.re.insertRows(at: [IndexPath(row: messages.count - 1, section: 0)], with: .automatic)
tableView.re.insertRows(at: [IndexPath(row: messages.count - 1, section: i)], with: .automatic)
tableView.endUpdates()
}

@IBAction func trashButtonTapped(_ sender: UIBarButtonItem) {
messages.removeAll()
sections.removeLast(max(0, sections.count - 1))
tableView.reloadData()
}
}

extension ViewController: UITableViewDataSource {

func numberOfSections(in tableView: UITableView) -> Int {
sections.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
sections[section].count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let messages = sections[indexPath.section]
(cell as? TableViewCell)?.configure(with: messages[indexPath.row])
return cell
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let messages = sections[indexPath.section]
let message = messages[indexPath.row]
print("willDisplay: \(message)")
}
}


Expand Down

0 comments on commit 88da462

Please sign in to comment.