在 UITableViewCell 中选择更改图像(swift 3 xcode)

Change image on selection in UITableViewCell(swift 3 xcode)

我的 tableViewCell 中有一个 imageView,我想在选择时更改它的图像。这是我的代码:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let myCell = tableView.cellForRow(at: indexPath) as! TableCell
    myCell.resourceIcons.image = UIImage(named: "RubiusResources2")
    tableView.deselectRow(at: indexPath, animated: true)

}

代码有效,但 tableView 下方不同部分中的其他一些行似乎也发生了变化。

编辑:

根据下面的评论,我得出了以下解决方案:

我首先创建了一个 2D bool 数组来表示我 table 拥有的部分和行的数量,并将它们全部设置为 false。

var resourceBool = Array(repeating: Array(repeating:false, count:4), count:12)

然后我创建了一个 if 语句来检查 indexPath 中的数组是 false 还是 true。这将是图像状态发生变化的地方。

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

    let myCell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! TableCell

    if (global.resourceBool[indexPath.section][indexPath.row] == false) {
        myCell.resourceIcons.image = global.systemResourceImages[0]
    } else if (global.resourceBool[indexPath.section][indexPath.row] == true) {
        myCell.resourceIcons.image = global.systemResourceImages[1]
    }

    return myCell
}

然后,在 didSelectRow 函数中,我将 indexPath 处的数组更改为 true 并重新加载 tableView 数据。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    global.resourceBool[indexPath.section][indexPath.row] = true
    tableView.reloadData()
    tableView.deselectRow(at: indexPath, animated: true)

}

根据我的理解,对象的状态必须始终在 cellForRow 中。

其中一个解决方案是您需要维护一个单独的所选行列表,并在 cellForRowAt 方法中比较它们。

代码看起来像这样。

var selectedArray : [IndexPath] = [IndexPath]()

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let myCell = tableView.cellForRow(at: indexPath) as! TableCell
    myCell.resourceIcons.image = UIImage(named: "RubiusResources2")
    tableView.deselectRow(at: indexPath, animated: true)

    if(!selectedArray.contains(indexPath))
    {
        selectedArray.append(indexPath)
    }
    else
    {
        // remove from array here if required
    }
}

然后在 cellForRowAt 中编写此代码以设置正确的图像

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

        if(selectedArray.contains(indexPath))
        {
            // use selected image
        }
        else
        {
            // use normal image
        }

        .
        .
        .
    }