1

Im building a chat App with Firebase,and I have a problem is after reloadData() will scroll top.

How can I to disable that?

This my code

func retrieveDataFromFirebase(){
    FIRDatabase.database().reference().child("share").child("post").observe(.value) { (snapshot:FIRDataSnapshot) in
        if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot]{
            self.key.removeAll()
            self.users.removeAll()
            for snap in snapshots{
                self.key.append(snap.key)
                if let dic = snap.value as? [String:AnyObject]{
                    let msg = Message()
                    msg.setValuesForKeys(dic)
                    self.users.append(msg)
                }

            }
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Kenny
  • 39
  • 1
  • 5
  • 1
    First, remove the DispatchQueue as it's not needed. Second, before reloading the tableView, get it's current scroll position. That property/value will vary depending on if your rows are all the same height or not so there's two ways that can be done. After reloading the tableView. scroll back to that position, as long as it's still within the range. See [Get Scroll Position](http://stackoverflow.com/questions/2795900/how-can-i-get-the-uitableview-scroll-position-so-i-can-save-it) – Jay Jan 22 '17 at 14:56

2 Answers2

1

Into the UIScrollView class (that is implemented by the UITableView) you have the scrollsToTop variable.

Try to set it to false.

Or you will need to create a delegate that deny scroll to top when you reload data.

Refs: https://developer.apple.com/reference/uikit/uiscrollview https://developer.apple.com/reference/uikit/uiscrollview/1619421-scrollstotop

https://developer.apple.com/reference/uikit/uiscrollviewdelegate/1619378-scrollviewshouldscrolltotop

0

Try scrolling your tableview to last index.

let lastCellIndexPath = NSIndexPath(forRow: yourArray.count-1, inSection: 0)
self.tableView.scrollToRowAtIndexPath(lastCellIndexPath, atScrollPosition: .Bottom, animated: false)
Yalcin Ozdemir
  • 524
  • 3
  • 7