ios - 表格 View 滚动更改选择

标签 ios swift

我查看了几个与此相关的 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/

相关文章:

ios - 如何删除应用程序图标角标(Badge),ios 10,swift

ios - EXC_BAD_INSTRUCTION 错误

Swift 3 KVO 观察 NSMutableSet 的变化(添加、删除、修改项)

generics - 将枚举添加到泛型类时 Xcode 构建错误?

ios - 在 Swift 中为 DebugPrintable 实现 debugDescription

ios - CGPointEqualToPoint 不起作用

iphone - 如何从 WebView 中获取电子邮件地址?

ios - 在iphone/ipad扬声器中录制音频

swift - 如何在 `NSURLSession` 超时时显示错误并终止应用程序?

ios - 如何正确调整通用应用程序在整个项目中使用的 UIView 的大小?