Last active
September 27, 2023 06:26
-
-
Save WorldDownTown/9ed681148e9224f7157c9e8620ce46b8 to your computer and use it in GitHub Desktop.
Insert rows in the top of UITableView without scrolling.
This file contains 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
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