我如何自动滚动表格视图? (迅速)

我添加了一个search栏到我的表格视图,当用户search,我希望表视图滚动到您键入的文本。

如何使滚动视图自动滚动?

这是我尝试,但我得到一个错误,说一个整数不能转换为索引path。 我该怎么办?

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

要么

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

您必须按以下方式调用方法scrollToRowAtIndexPath

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

上面的例子假设你只有一个部分。 我希望这可以帮助你。

对于Swift 3:

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

对于Swift 3(Xcode 8.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: UITableViewScrollPosition.middle, animated: true) 

如果你想自动向下滚动:

 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 2.0版本,根据Thiago早些时候在这个线程中的代码,滚动到多个部分的最后一行:

 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) 

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() } }