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



我的tableView有一个奇怪的问题。我有一个音轨列表和一个到音频播放器的分段,以便在特定行播放选定的音轨。一切都很好!

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

但当我运行它时,它不仅会更改我选择的索引路径上的行的颜色,还会更改索引路径+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、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上运行。

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

这可能是因为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
}

然后在你的单元格中ForRowAtIndexPath方法:

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
}

最新更新