UITableViewCell对indexPath的更改不正确

时间:2018-03-06 15:05:06

标签: ios swift tableview

我尝试使用UITableViewCell的accessoryType属性来单击时检查单元格,但是当选择单元格时,复选标记为不同的单元格设置了几次,例如当我选择row [0],row [0]和row [8]以及row时[17] AccessoryType设置为选中标记!

MarketPlace

1 个答案:

答案 0 :(得分:1)

对于单选,您需要在viewController变量

中跟踪所选的indexPath
var selectedIndexPath : IndexPath?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    self.selectedIndexPath = indexPath
    tableView.reloadData()
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "npCell", for: indexPath) as! NewPlaylistTableViewCell

    cell.mTitle.text = musics[indexPath.row]["title"] as! String?
    cell.mArtist.text = musics[indexPath.row]["artist"] as! String?

    cell.accessoryType = .none
    cell.selectionStyle = .none
    if(indexPath == selectedIndexPath) {
       cell.accessoryType = .checkmark
    }

    return cell
}

更好(避免重新加载整个UITableView)

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let previousSelectedIndexPath = self.selectedIndexPath
        self.selectedIndexPath = indexPath
        if(previousSelectedIndexPath != nil) {
            self.tableView.reloadRows(at: [previousSelectedIndexPath!,self.selectedIndexPath!], with: .automatic)
        }else{
            self.tableView.reloadRows(at: [self.selectedIndexPath!], with: .automatic)
        }
        self.tableView.reloadData()
    }

更新,允许多项选择

对于多重选择,您应该跟踪Dictionary中的选定单元格,以便更快地访问选定和未选定的indexPath,允许您使用多个部分,因为我们的Dictionary的键值是由(IndexPath.section)+形成的字符串+ (IndexPath.row)始终是唯一组合

var selectedIndexPaths : [String:Bool] = [:]

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let currentIndexPathStr = "\(indexPath.section)\(indexPath.row)"
    if(self.selectedIndexPaths[currentIndexPathStr] == nil || !self.selectedIndexPaths[currentIndexPathStr]!) {
        self.selectedIndexPaths[currentIndexPathStr] = true
    }else{
        self.selectedIndexPaths[currentIndexPathStr] = false
    }
    self.tableView.reloadRows(at: [indexPath], with: .automatic)
}


public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "npCell", for: indexPath) as! NewPlaylistTableViewCell

        cell.mTitle.text = musics[indexPath.row]["title"] as! String?
        cell.mArtist.text = musics[indexPath.row]["artist"] as! String?

        cell.accessoryType = .checkmark
        let currentIndexPathStr = "\(indexPath.section)\(indexPath.row)"
        if(self.selectedIndexPaths[currentIndexPathStr] == nil || !self.selectedIndexPaths[currentIndexPathStr]!)  {
           cell.accessoryType = .none
        }

        return cell
    }

<强>结果

enter image description here