簡體   English   中英

存儲TableView選定的行

[英]Store TableView selected Row

我有一個表格視圖,我想更改所選表格視圖的選定單元格顏色,並且在滾動表格視圖時不更改單元格顏色。 有我的代碼:

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()
            }
        }

滾動表視圖時,這就是代碼崩潰。

您的代碼對我來說似乎很奇怪。 您無需每次選擇所有其他單元格的背景顏色。 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
    }
}

然后在您的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