Reputation: 1037
I have used UITableView.refreshControl with large titles. I am trying to mimic the way the native Mail app works with pull to refresh. The refresh control, for me, moves and doesn't stay stuck at the top of the screen like the Mail app does. Here is a playground:
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
public init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var refresh: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.backgroundColor = .clear
refreshControl.tintColor = .black
refreshControl.addTarget(self, action: #selector(refreshIt), for: .valueChanged)
return refreshControl
}()
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.refreshControl = refresh
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
private var data: [Int] = [1,2,3,4,5]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// Add tableview
addTableView()
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "View Controller"
}
private func addTableView() {
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.leftAnchor.constraint(equalTo: view.leftAnchor),
tableView.rightAnchor.constraint(equalTo: view.rightAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
@objc func refreshIt(_ sender: Any) {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.refresh.endRefreshing()
self.data = [6,7,8,9,10]
self.tableView.reloadData()
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "Row \(data[indexPath.row])"
return cell
}
}
let vc = ViewController()
let nav = UINavigationController(rootViewController: vc)
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = nav
How can I get the spinner to stick to the top, and have it behave like the Mail app does? Also the navigation title does this weird thing where it moves back slower than the table data and causes some overlap to happen... Any help is appreciated!
EDIT JUNE 7, 2020
I switched to using a diffable datasource which fixes the overlap animation, however, there is still this weird glitch right when the haptic feedback occurs and causes the spinner to shoot up to the top and back down, so my original question still remains - how do we get the spinner to stay pinned at the top like the mail app. Thanks for taking a look at this unique issue :)!!!
Upvotes: 10
Views: 2065
Reputation: 881
I think the problems is tableView.reloadData()
. You can change it to tableView.beginUpdates()
and tableView.endUpdates()
In this demo, I will create an extension for easier for tableView to reload with beginUpdate and enUpdates.
extension UITableView {
func reloadWithNewData<T:Equatable>(_ newDatas : [T], _ oldDatas : [T],_ animation : UITableView.RowAnimation) {
var deleteOnes : [IndexPath] = []
var appendOnes : [IndexPath] = []
for i in 0 ..< oldDatas.count {
for j in 0 ..< newDatas.count {
if newDatas[j] == oldDatas[i] {
break
}
if j == newDatas.count - 1 {
deleteOnes.append(IndexPath(row: i, section: 0))
}
}
}
for i in 0 ..< newDatas.count {
for j in 0 ..< oldDatas.count {
if newDatas[i] == oldDatas[j] {
break
}
if j == oldDatas.count - 1 {
appendOnes.append(IndexPath(row: i, section: 0))
}
}
}
self.beginUpdates()
self.deleteRows(at: deleteOnes, with: animation)
self.insertRows(at: appendOnes, with: animation)
self.endUpdates()
}
}
Then you just need to change for function refreshIt()
@objc func refreshIt(_ sender: Any) {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.refresh.endRefreshing()
let oldData = self.data
self.data = [6,7,8,9,10]
self.tableView.reloadWithNewData(self.data, oldData, .fade)
}
}
Happy coding
Upvotes: 0
Reputation: 257493
The reason is in used reloadData
which synchronously drops & rebuilds everything thus breaking end refreshing animation.
The possible solution is to give time to end animation and only then perform reload data.
Tested with Xcode 11.4 / Playground
Modified code:
@objc func refreshIt(_ sender: Any) {
// simulate loading
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.refresh.endRefreshing() // << animating
// simulate data update
self.data = [6,7,8,9,10]
// forcefully synchronous, so delay a bit
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.tableView.reloadData()
}
}
}
Alternate approach, if you known modified data structure, would be to use beginUpdate/endUpdate
pair
@objc func refreshIt(_ sender: Any) {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.refresh.endRefreshing()
self.data = [6,7,8,9,10]
// more fluent, but requires knowledge of what is modified,
// in this demo it is simple - first section
self.tableView.beginUpdates()
self.tableView.reloadSections(IndexSet([0]), with: .automatic)
self.tableView.endUpdates()
}
}
Upvotes: 2
Reputation: 1142
I don't really know how to answer the first question, but since you asked 2 questions I'll go ahead and try to help you with the second in the meanwhile.
The problem with the rows getting to the top too fast is due to the use of tableView.reloadData()
.
That is always done without animation, so what is happening is to be expected.
What you could do is to use other methods on the table view, like insert or delete rows like this:
@objc func refreshIt(_ sender: Any) {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.refresh.endRefreshing()
let newData = [6,7,8,9,10]
let newIndexPaths = newData.enumerated().map{IndexPath(row: self.data.count+$0.offset, section: 0)}
self.data.append(contentsOf: newData)
self.tableView.insertRows(at: newIndexPaths, with: .automatic)
}
}
In this way the rows will be added with an animation and the scroll down animation won't be interrupted by any reloadData()
.
If you don't have only rows to add (or delete) and maybe have to do some sort of combination of both, then you can use the performBatchUpdates method to do both add and delete in the same animation block. (iOS 11+)
That's, of course, only viable if you are able to calculate the indexes of the items to add and delete. Keep in mind that the amount of rows you add and delete should always be reflected by the actual change in your data structure, or you'll have a nasty exception thrown by the table view.
Anyway that should always be feasible, but if you want it out of the box you could use iOS 13 diffable data source or, if you want it even before iOS 13, you could use instagram's IGListKit.
Both pretty much use the same concept of diffing your array of input and automatically detect deletions and inserts. So changing the array will automatically reflect in the animated change in your tableView rows. Of course both of them are very different ways of implementing a tableView, so you really can't just change a little piece of your code to make it work.
Hope this can help.
Upvotes: 0