Created
February 11, 2021 22:26
-
-
Save paulw11/1d3f043e610f836d35927040b8258085 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewController: UIViewController { | |
var max = 0.0 | |
var data:[Double] = [13,32,43,56,91,42,26,17,63,41,73,54,26,87,64,33,26,51,99,85,57,43,30,33,20] | |
@IBOutlet weak var tableView: UITableView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.backgroundColor = .red | |
self.tableView.dataSource = self | |
self.tableView.delegate = self | |
self.tableView.reloadData() | |
} | |
private func calculate() { | |
// calculate the max of visible cells | |
if let indexes = tableView.indexPathsForVisibleRows { | |
max = indexes | |
.map { data[$0.row] } | |
.reduce(0) { Swift.max($0,$1) | |
} | |
print("New max is \(max)") | |
} | |
} | |
private func updateVisibleCells() { | |
for indexPath in self.tableView.indexPathsForVisibleRows ?? [] { | |
if let cell = self.tableView.cellForRow(at: indexPath) { | |
cell.textLabel?.text = "\(data[indexPath.row]) : \(max)" | |
} | |
} | |
} | |
} | |
extension ViewController: UITableViewDataSource, UITableViewDelegate { | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
data.count | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(withIdentifier: "default")! | |
cell.textLabel?.text = "\(data[indexPath.row]) : \(max)" | |
return cell | |
} | |
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { | |
return 64 | |
} | |
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { | |
self.calculate() | |
DispatchQueue.main.async { | |
self.updateVisibleCells() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment