ios - TableView 复制上的复选框,Swift,iOS

标签 ios uitableview select checkbox

我有一个 tableView,当它被选中时会从一张图片更改为另一张图片。这一切都很好,但是当我选择一个 tableCell 时它改变了图像,但是当我滚动它时它也改变了我没有选择的另一个单元格的图像。

下面是我的代码。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FeaturesCell") as! FeaturesCell

    cell.featuresLabel.text = self.items[indexPath.row]

    return cell

}

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

     pickedFeatures.append(items[indexPath.row])

    let cell = tableView.cellForRow(at: indexPath) as! FeaturesCell

    cell.checkImage.image = #imageLiteral(resourceName: "tick-inside-circle")

}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    pickedFeatures.remove(at: pickedFeatures.index(of: items[indexPath.row])!)

    let cell = tableView.cellForRow(at: indexPath) as! FeaturesCell

    cell.checkImage.image = #imageLiteral(resourceName: "No-tick-inside-circle")
}

如果我在 did select 函数中使用 detqueureusable 单元格,那么它在选择时根本不会改变图片。

最佳答案

您可以使用tableView.dequeueReusableCell(_),问题是,您没有维护所选单元格的状态。

示例:

class viewController: UIVieWController, UITableViewDelegate, UITableViewDataSource {

    var selectedCellList  = [IndexPath]()

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "FeaturesCell") as! FeaturesCell

        cell.featuresLabel.text = self.items[indexPath.row]

        if let _ = selectedCellList.index(of: indexPath) {
            // Cell selected, update check box image with tick mark
             cell.checkImage.image = #imageLiteral(resourceName: "tick-inside-circle")
        } else {
            // Cell note selected, update check box image without tick mark
            cell.checkImage.image = #imageLiteral(resourceName: "No-tick-inside-circle")
        }
        return cell
    }

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

        pickedFeatures.append(items[indexPath.row])

        if let index = selectedCellList.index(of: indexPath) {
            selectedCellList.remove(at: index)
        } else {
            selectedCellList.append(indexPath)
        }
        tableView .reloadRows(at: [indexPath], with: .automatic)
    }

}

关于ios - TableView 复制上的复选框,Swift,iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45390705/

相关文章:

ios - UITableview 充满图像 : too much space between images

mysql - 使用列中的值作为 LIKE 语句中表达式的值

ios - 使用 UIView.transition() 方法的幻灯片过渡

ios - iOS 中具有大小等级的自定义字体

ios - 如何将 Hstack 内部的 View 与相对侧对齐?

ios - 如何为 UITableView 创建 IBAction?

ios - 如何在 UITableVIewCell 中进行 API 调用

mysql - 需要有关求和时间的 MySQL 语句语法的帮助

select - DB2:通过干扰 Select 子句中的子查询进行分组

objective-c - iOS 4.3 的 NSDate 完整日期