UITableView deleterows scroll to top

折月煮酒 提交于 2019-12-13 08:10:56

问题


I made a query to delete specified rows in UITableView but the problem when the deleteRows is called the UITableView scroll to top so how to prevent it scrolling to top? and why it scroll to top!

I try called a method to force it scroll to down but the tableview scroll to top first after return the code of remove

FIRDatabase.database().reference().child("messages").child(self.roomId).observe(.childRemoved, with: {(snap) in
        print("child Removed")
        for msg in self.messageArray {
            let message: NSDictionary = msg as! NSDictionary
            let messageContent: [String: Any] = message as! [String: Any]
            if messageContent["messageID"] as! String == snap.key {
                let indexRemoved = self.messageArray.index(of: msg)
                self.messageArray.remove(msg)
                self.userArray.removeObject(at: indexRemoved)
                let indexPath = IndexPath(row: indexRemoved, section: 0)
                print(indexPath)
                self.conversationTableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none)
                break;
            }   
        }
        })

回答1:


Please be sure you are not using table view method like 'estimatedHeightFor...' to calculate hight to scroll table view after row delete. One more point to be sure is, reloadData method should not use when deleting row from table view if you don't want to table scrolling.

If all are good then on deleting a particular row, table view will move all rows up to fill deleted row empty space.




回答2:


There are a few issues with the code that can be easily corrected.

First before doing anything, grab the current scroll position of the first visible item (given the cells are the same size)

let savedIndex = myTableView.indexPathsForVisibleRows?.first

then once the row is deleted from the array and you reload the tableview, you can return to where it was with

myTableView.scrollToRowAtIndexPath(savedIndex, atScrollPosition: .Top, animated: false)

If you need another option (variable heights), you can use

tableView.contentOffset.y;

Also, there's no need to iterate over the entire array to find the row to delete from it. Assuming the Firebase nodes(s) data are stored in the array as a class, in the array with the Firebase key as a property of each class, you can simply get the index of that element in the array and remove it. Here's an option

let key = snapshot.key

if let index = self.myArray.indexOf({$0.firebaseKey == key}) {
     self.myArray.removeAtIndex(index)
     self.myTableView.reloadData()
}

This object would look like:

class MyClass {
    var firebaseKey: String?
    var some_var: String?
    var another_var: String?
}


来源:https://stackoverflow.com/questions/41502325/uitableview-deleterows-scroll-to-top

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!