自动滚动到具有特定值的单元格

我有一个这样的表视图中的数字列表。

在这里输入图像说明

正如你所看到的数字重复。 我们来看一组重复的数字。 所以有1s组,2s组等等。

我想要做的是当应用程序启动时,我需要自动滚动到指定组的开始位置。 在进一步解释之前,这里是我的代码。

import UIKit class TableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate { private var scrollToTime = true private var items = [Int]() private var groupNoToScroll = 12 override func viewDidLoad() { super.viewDidLoad() items = [1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 7, 8, 8, 8, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 14, 14, 14, 14, 15, 15, 16, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20, 21, 22, 22, 23, 23, 23] } // MARK: - UITableViewDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell cell.textLabel?.text = String(items[indexPath.row]) return cell } // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let lastRow = tableView.indexPathsForVisibleRows()?.last as NSIndexPath if indexPath.row == lastRow.row { if scrollToTime == true { let indexPath = NSIndexPath(forRow: groupNoToScroll, inSection: 0) tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true) scrollToTime = false } } } } 

我已经为variablesgroupNoToScroll分配了值12。 这意味着应用程序启动时,我希望表视图自动滚动到12s组的单元格的开始。

但目前我的代码是滚动到第12个单元格,而不是具有 12的单元格。我的问题是如何检查单元格的值,并滚动到我指定的数字?

您可以使用查找项目的索引(这将是行),然后滚动到该索引。
find函数返回数组中特定元素的索引。

 if let index = find(items, groupNoToScroll) { let indexPath = NSIndexPath(forRow: index, inSection: 0) tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true) } 

Swift 3.0

  let indexPath = NSIndexPath(forRow: 5, inSection: 0) tableView.scrollToRow(at: indexPath, at: .top, animated: true) 

Swift 4:

 let indexPath = IndexPath(row: row, section: section) tableView.scrollToRow(at: indexPath, at: .top, animated: true) 

(首先,当然,您必须根据要滚动到的单元格将值分配给行和部分)

这样做是为了find数组中等于groupNoToScroll的第一个元素。 然后,去那一行。

  var rowToGoTo:Int = 0 //Rather use the Swift find function. for x in items{ if x == groupNoToScroll{ break } rowToGoTo++ } let lastRow = tableView.indexPathsForVisibleRows()?.last as NSIndexPath if indexPath.row == lastRow.row { if scrollToTime == true { let indexPath = NSIndexPath(forRow: rowToGoTo, inSection: 0) tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true) scrollToTime = false } } 

但我会build议这样做viewDidAppear。

正如Isuru所指出的那样,使用find函数。

Interesting Posts