我查看了几个与此相关的 StackOverflow 问题,但似乎还没有很好地理解这个概念。
我有一个表格 View ,其中包含几个使用枚举填充的单元格。当我向下滚动行时,表中较低的另一行被选中。我实现了以下方法:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("activityCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = activities[indexPath.item].rawValue;
return cell;
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell = tableView.cellForRowAtIndexPath(indexPath);
cell?.selected = true;
}
我知道单元格是可重复使用的,但我无法正确理解这个概念及其应用方式。
你能给我一些帮助吗?
干杯
最佳答案
如果您要重用单元格,请按照您所做的方式在indexPath的didSelectRowAtIndexPath
中将单元格设置为selected
,这将使重用的单元格也反射(reflect)更改后的 selected
属性。相反,我建议向您的事件对象添加一个 bool selected
属性,以便可以在 cellForRowAtIndexPath:
中进行选择更改,例如:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("activityCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = activities[indexPath.item].rawValue
cell?.selected = activities[indexPath.item].selected
return cell;
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
activities[indexPath.item].selected = true
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
}
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
activities[indexPath.item].selected = false
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
}
关于ios - 表格 View 滚动更改选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27471261/