nachshon f
nachshon f

Reputation: 3680

How do i automatically scroll in a table view? (Swift)

I added a search bar to my table view, and as the user searches, I want the table view to scroll to the text that your typed.

How do I make the scroll view scroll automatically?

This is what I tried, but I get an error saying that an Integer is not convertible to an index Path. What should I do?

self.tableview.scrollToRowAtIndexPath(1, atScrollPosition: UITableViewScrollPosition.Middle, animated: true)

or

self.tableview.scrollToNearestSelectedRowAtScrollPosition(scrollPosition: UITableViewScrollPosition.Middle, animated: true)

Upvotes: 20

Views: 34355

Answers (7)

Clean Coder
Clean Coder

Reputation: 562

> To start scrolling:

private var autoTimer = Timer()

private func startAutoScroll(duration: TimeInterval, direction: ScrollDirectionType) {
        var currentOffsetY = tableView.contentOffset.y
        var shouldFinish = false
        autoTimer = Timer.scheduledTimer(withTimeInterval: duration, repeats: true, block: { [weak self] (_) in
            guard let self = self else { return }
            switch direction {
            case .top:
                currentOffsetY = (currentOffsetY - 10 < 0) ? 0 : currentOffsetY - 10
                shouldFinish = currentOffsetY == 0
            case .bottom:
                let highLimit = self.tableView.contentSize.height - self.tableView.bounds.size.height
                currentOffsetY = (currentOffsetY + 10 > highLimit) ? highLimit : currentOffsetY + 10
                shouldFinish = currentOffsetY == highLimit
            default: break
            }
            DispatchQueue.main.async {
                UIView.animate(withDuration: duration * 2, animations: {
                    self.tableView.setContentOffset(CGPoint(x: 0, y: currentOffsetY), animated: false)
                }, completion: { _ in
                    if shouldFinish { self.stopScrolling() }
                })
            }
        })
    }

> To End Scrolling

 private func stopScrolling() {
    if autoTimer.isValid {
        view.layer.removeAllAnimations()
        autoTimer.invalidate()
    }
}

Upvotes: 0

Irshad Qureshi
Irshad Qureshi

Reputation: 819

For Swift 5 ( Xcode 11.2.1 ):

    let numberOfSections = self.tableView.numberOfSections
    let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)

    let indexPath = IndexPath(row: numberOfRows-1 , section: numberOfSections-1)
    self.tableView.scrollToRow(at: indexPath, at: .middle, animated: true)

For Swift 2:

    let numberOfSections = self.tableView.numberOfSections
    let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)

    let indexPath = IndexPath(row: numberOfRows-1 , section: numberOfSections-1)
    self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.middle, animated: true)

Upvotes: 12

Thiago Arreguy
Thiago Arreguy

Reputation: 2847

If you want scroll down automatically:

numberOfSections = tableView.numberOfSections()
let numberOfRows = tableView.numberOfRowsInSection(numberOfSections-1)

var indexPath = NSIndexPath(forRow: numberOfRows, inSection: numberOfSections)
self.tableview.scrollToRowAtIndexPath(indexPath, 
               atScrollPosition: UITableViewScrollPosition.Middle, animated: true)

Swift 4:

let numberOfSections = tableView.numberOfSections
let numberOfRows = tableView.numberOfRows(inSection: numberOfSections - 1)

let indexPath = NSIndexPath(row: numberOfRows, section: numberOfSections)
self.tableView.scrollToRow(at: indexPath as IndexPath,
                                  at: UITableView.ScrollPosition.middle, animated: true)

Upvotes: 5

Victor Sigler
Victor Sigler

Reputation: 23449

You have to call the method scrollToRowAtIndexPath in the following way :

var indexPath = NSIndexPath(forRow: numberOfRowYouWant, inSection: 0)
self.tableview.scrollToRowAtIndexPath(indexPath, 
               atScrollPosition: UITableViewScrollPosition.Middle, animated: true)

The above example assume you have only one section. I hope this help you.

For Swift 3:

let indexPath = NSIndexPath(item: numberOfRowYouWant, section: 2)
tableView.scrollToRow(at: indexPath as IndexPath, at: UITableViewScrollPosition.middle, animated: true)

For Swift 4:

let indexPath = NSIndexPath(item: numberOfRowYouWant, section: 2)
tableView.scrollToRow(at: indexPath as IndexPath, at: UITableView.ScrollPosition.middle, animated: true)

Upvotes: 31

Swift 4:

let indexPath = IndexPath(row: numberOfRowYouWant, section: 0) 

self.verbsTable.scrollToRow(at: indexPath, at: UITableViewScrollPosition.middle, animated: true)

Upvotes: -1

Faris
Faris

Reputation: 1236

SWIFT 4

/* Variables */
  var scrollTimer = Timer()


//  AN AUTOMATIC SCROLL OF THE YOUT IMAGE
scrollTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(automaticScroll), userInfo: nil, repeats: true)




// MARK: - SCROLLVIEW DELEGATE: SHOW CURRENT PAGE IN THE PAGE CONTROL
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let pageWidth = containerScrollView.frame.size.width
    let page = Int(floor((containerScrollView.contentOffset.x * 2 + pageWidth) / (pageWidth * 2)))
    pageControl.currentPage = page

}

// MARK: - AUTOMATIC SCROLL
@objc func automaticScroll() {
    var scroll = containerScrollView.contentOffset.x
    if scroll < CGFloat(view.frame.size.width) * CGFloat(numberOfImages-1) {
        scroll += CGFloat(view.frame.size.width)
        containerScrollView.setContentOffset(CGPoint(x: scroll, y:0), animated: true)
    } else {
        // Stop the timer
        scrollTimer.invalidate()
    }
}

Upvotes: 0

xke
xke

Reputation: 1093

Here's the Swift 2.0 version to scroll to the last row of multiple sections, based on the code from Thiago earlier in this thread:

let numberOfSections = self.tableView.numberOfSections
let numberOfRows = self.tableView.numberOfRowsInSection(numberOfSections-1)

print ("scrolling to bottom row \(numberOfRows)")

let indexPath = NSIndexPath(forRow: numberOfRows-1, inSection: numberOfSections-1)
self.tableView.scrollToRowAtIndexPath(indexPath,
                        atScrollPosition: UITableViewScrollPosition.Middle, animated: true)

Upvotes: 3

Related Questions