我一直在尝试确定表格 View 顶部的第三个单元格。基本上,这意味着,从顶部开始的第三个单元格看起来总是与其他单元格不同(即文本颜色会改变等)。 我想既然单元格被重用了,我总是能够像这样访问第三个单元格:
if (indexPath.row == 2) {
}
不幸的是,它似乎并没有那样工作。当我继续打印 indexPath.row
时,数字继续从 0 一直增加到 12... 现在这是可以理解的,因为它是 row
单元格,但是我怎样才能始终从顶部访问第三行。这是我最初采用的方法:
override func scrollViewDidScroll(scrollView: UIScrollView) {
let indexPath: NSIndexPath = self.tableView.indexPathsForVisibleRows![0]
if (indexPath.row == 2) {
// Print or whatever
}
}
}
那么我怎样才能始终从 tableView
的顶部访问第三行呢?
谢谢!
最佳答案
这是一个示例项目。我尝试在模拟器中运行它,它似乎工作正常。
这是 XCode 的屏幕截图,因此您可以看到 Main.Storyboard。
这里还有一份 ViewController.swift 中的代码副本:
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var indexOfThirdVisible: Int!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
// Do any additional setup after loading the view, typically from a nib.
self.navigationController?.navigationBar.barStyle = .BlackTranslucent
self.navigationController?.navigationBar.tintColor = UIColor.orangeColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let indexPath = self.tableView.indexPathsForVisibleRows![0]
indexOfThirdVisible = indexPath.row + 2
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: indexOfThirdVisible, inSection: indexPath.section)) as! TableViewCell
cell.label.textColor = UIColor.orangeColor()
let cellAbove = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: indexOfThirdVisible - 1, inSection: indexPath.section)) as! TableViewCell
let cellBelow = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: indexOfThirdVisible + 1, inSection: indexPath.section)) as! TableViewCell
cellAbove.label.textColor = UIColor.whiteColor()
cellBelow.label.textColor = UIColor.whiteColor()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
// heightForRowAtIndexPath
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
// configure cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")!
return cell
}
}
这是 TableViewCell.swift:
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet weak var label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
抱歉,如果缩进搞砸了。 祝您今天愉快,如果您需要更多帮助,请告诉我!
关于swift - TableView 从顶部确定第三个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34782518/