【发布时间】:2015-01-20 10:59:44
【问题描述】:
我在这样的表格视图中有一个数字列表。
如您所见,数字是重复的。让我们将一组重复数字视为一个组。所以有一组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
}
}
}
}
我为变量groupNoToScroll 分配了值12。这意味着当应用程序启动时,我希望表格视图自动滚动到 12s 组的单元格的开头。
但目前我的代码所做的是滚动到第 12 个单元格,而不是具有 值 12 的单元格。我的问题是如何检查单元格的值并滚动到我指定?
【问题讨论】:
-
你将不得不遍历你的数组并获得
groupNoToScroll第一次出现的索引。 -
然而,重写 tableView:willDisplayCell: 并不是一个好主意。你到底在做什么?
-
@HermannKlecker 我想在加载所有单元格后进行自动滚动。所以根据this 的回答,
willDIsplayCell是我需要检查的地方。有没有更好的方法来解决这个问题? -
否 willDisplayCell 不是为此而设计的。您将面临无限循环的风险。我只需使用 scrollToRowAtIndexPath 滚动到 viewDidLoad 中的相关单元格。工作正常。我做了很多。
标签: ios uitableview swift scroll autoscroll