Swift UITableViewCell的问题:更改所选行的背景颜色

时间:2015-02-23 15:05:54

标签: swift tableviewcell uibackgroundcolor

我的tableView有一个奇怪的问题。 我有一个音轨列表和一个音频播放器的segue,以便在特定行播放选定的音轨。一切正常!

我想更改表格中所选行的背景颜色,这样,一旦用户播放音频并返回到曲目列表(我的表视图控制器),他就可以看到哪些是先前选择的行

但是当我运行时它不仅改变了我选择的索引路径的行的颜色,还改变了索引路径+10处的项目的颜色。 如果我选择第一行,它会改变索引处行的颜色:0,10,20,30 ......

为了更改所选单元格的颜色,我执行了以下操作:

// MARK: - Navigation
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.performSegueWithIdentifier("audioPlayer", sender: tableView)

    var selectedCell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath) as CustomTableViewCell
    selectedCell.contentView.backgroundColor = UIColor.greenColor()
    selectedCell.backgroundColor = UIColor.blueColor()

请找到我的问题的截图,我只选择了三行:1,3,5但我选择了1,3,5,11,13,15,21,23等等......: https://www.dropbox.com/s/bhymu6q05l7tex7/problemaCelleColore.PNG?dl=0

有关详细信息 - 如果有帮助 - 这是我的自定义表视图类:

    import UIKit

    class CustomTableViewCell: UITableViewCell {

@IBOutlet weak var artista: UILabel!

@IBOutlet weak var brano: UILabel!

var ascoltato = false

@IBOutlet weak var labelRiproduciAscoltato: 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
}

func setCell(artista: String, brano: String){
    self.artista.text = artista
    self.brano.text = brano
}

   }  // END MY CUSTOM TABLE VIEW CELL

这是我的TableViewController中的方法cellForRowAtIndexPath:

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

    var tracks : Brani  //Brani is my custom Object for handle my tracks

    cell.setCell(tracks.title!, brano: tracks.author!)


    return cell

}

我正在使用iOS 7.1在iPad Air上运行。

提前感谢您提出与我的问题相关的任何建议或建议。

1 个答案:

答案 0 :(得分:0)

这可能是因为UITableViewCells被回收了。这意味着以前选择的tableViewCell被较低索引处的单元格重用。这是UITableView的预期行为并且有意义,因为它节省了内存使用量。要解决此问题,您需要让数据源跟踪选择的单元格,并相应地更新单元格的背景颜色。

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("audioPlayer", sender: tableView)
//datasource is updated with selected state
//cell is updated with color change
}

然后在你的cellForRowAtIndexPath方法中:

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

    var tracks : Brani  //Brani is my custom Object for handle my tracks

    cell.setCell(tracks.title!, brano: tracks.author!)
    //update cell style here as well (by checking the datasource for selected or not). 

    return cell
}
相关问题