Im implementing a UITableView
and I would like for the table view to automatically scroll up to the top once the user begins scrolling. I have used logic similar to this post to detect the direction that the user is scrolling. When the user begins to scroll up the function below detects the scroll but table.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
goes very slowly and stops part way up to the top of the cell. How can I fix this.
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
print("Dragging has ended")
//print("lastContentOffSet: \(self.lastContentOffset)")
if (self.lastContentOffset < scrollView.contentOffset.y) {
// moved to top
print("Scrolled down")
} else if (self.lastContentOffset > scrollView.contentOffset.y) {
// moved to bottom
print("Scrolled up")
table.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
} else {
// didn't move
}
}
Below is the code in its entirety.
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var table:UITableView!
@IBOutlet weak var photosButton: UIButton!
var lastContentOffset: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
table.delegate = self
table.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell = UITableViewCell()
if indexPath.row == 1{
cell = table.dequeueReusableCell(withIdentifier: "cameraCell", for: indexPath) as! cameraCell
cell.backgroundColor = .red
}else{
cell = table.dequeueReusableCell(withIdentifier: "photoAlbumCell", for: indexPath) as! photoAlbumCell
cell.backgroundColor = .blue
}
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UIScreen.main.bounds.height
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
print("Scrolling began")
self.lastContentOffset = scrollView.contentOffset.y
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
print("Dragging has ended")
if (self.lastContentOffset < scrollView.contentOffset.y) {
// moved to top
print("Scrolled down")
} else if (self.lastContentOffset > scrollView.contentOffset.y) {
// moved to bottom
print("Scrolled up")
table.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
} else {
// didn't move
}
}
@IBAction func photoAlbumButton(_ sender: UIButton) {
table.scrollToRow(at: IndexPath(row: 1, section: 0), at: .top, animated: true)
}
}
class cameraCell:UITableViewCell{
override func awakeFromNib() {
super.awakeFromNib()
}
}
class photoAlbumCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
}
}