Skip to content

Instantly share code, notes, and snippets.

@WorldDownTown
Last active September 27, 2023 06:26
Show Gist options
  • Save WorldDownTown/9ed681148e9224f7157c9e8620ce46b8 to your computer and use it in GitHub Desktop.
Save WorldDownTown/9ed681148e9224f7157c9e8620ce46b8 to your computer and use it in GitHub Desktop.
Insert rows in the top of UITableView without scrolling.
import UIKit
final class ViewController: UITableViewController {
private var names: [String] = (50...99).map { String($0) }
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
self.appendCells()
}
}
private func appendCells() {
let oldContentHeight: CGFloat = tableView.contentSize.height
let oldOffsetY: CGFloat = tableView.contentOffset.y
names = (0...49).map { String($0) } + names
tableView.reloadData()
let newContentHeight: CGFloat = tableView.contentSize.height
tableView.contentOffset.y = oldOffsetY + (newContentHeight - oldContentHeight)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = names[indexPath.row]
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment