简体   繁体   English

存储TableView选定的行

[英]Store TableView selected Row

I have a table view, I want to change selected table view selected cell color, and cell color not changed when scroll table view. 我有一个表格视图,我想更改所选表格视图的选定单元格颜色,并且在滚动表格视图时不更改单元格颜色。 there is my code: 有我的代码:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath 
indexPath: NSIndexPath) {
  let selectCell = tableView.indexPathForSelectedRow
        self.selectedCell.append(selectCell!)
 for i in selectedCell
        {
            if(!(i .isEqual(indexPath)))
            {
                let currentCell = tableView.cellForRowAtIndexPath(i)! as UITableViewCell

                currentCell.backgroundColor = UIColor.lightGrayColor()
            }
        }

that's code crash when scroll table view. 滚动表视图时,这就是代码崩溃。

Your code seems very strange to me. 您的代码对我来说似乎很奇怪。 you don't need to set the background color of all other cells each time one is selected. 您无需每次选择所有其他单元格的背景颜色。 Define your celectedCells as dictionary of type Int:Bool so you can set it to true for each indexpath.row like this: celectedCells定义为Int:Bool类型的字典,这样就可以将每个indexpath.row值设置为true ,如下所示:

var selectedCells = [Int: Bool]()

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        cell.backgroundColor = UIColor.lightGrayColor()
        selectedCells[indexPath.row] = true
    }
}

and then in your cellForRowAtIndexPath method check that dictionary to set the backgroundColor, like this: 然后在您的cellForRowAtIndexPath方法中检查该字典以设置backgroundColor,如下所示:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("YourCellIdentifier", forIndexPath: indexPath)

    if selectedCells[indexPath.row] == true {
        // Color for selected cells
        cell.backgroundColor = UIColor.lightGrayColor()
    } else {
        // Color for not selected cells
        cell.backgroundColor = UIColor.whiteColor()
    }
    //Rest of your Cell setup

    return cell
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM