表视图确实选择了处理复选框图像的方法

时间:2018-03-02 07:23:34

标签: ios swift uitableview

我有一个包含三个单元格的表格视图,其中包含标签和一个图像(复选框)。现在我选择任何单元格。单独的特定单元格图像(复选框)需要tick.png。其余两个单元格图像应为untick.png

但是现在如果我选择第一个细胞然后第一个细胞图像得到tick.png.Then如果我选择第二个和第三个细胞。那个细胞图像也得到tick.png

但我只需要一个图像需要tick.png。我选择的特定单元格图像需要tick.png哪个表视图单元格。剩下的两个单元格图像应该是{{1} }}

我的代码:

untick.png

3 个答案:

答案 0 :(得分:2)

如果我理解正确,您在任何给定时间只需要一个复选标记。如果这是真的,那么你只需在视图控制器中设置一个属性,如下所示:

var checkedRow: Int

并在tableView(_:didSelectRowAt:)中设置行索引。通过将其设置为-1,您将禁用所有复选标记。然后在tableView(_:, cellForRowAt:)中,如果indexPath.row等于checkedRow,您将有条件地启用单元格的复选标记:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    checkedRow = indexPath.row
    tableView.reloadData()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ViewCell
    if indexPath.row == checkedRow {
        cell.suggestionImg.image = UIImage(named: "tick.png")
        cell. suggestionLbl.text = "<ticked text>"
    } else {
        cell.suggestionImg.image = UIImage(named "untick.png")
        cell. suggestionLbl.text = "<unticked text>"
    }
    return cell
}

答案 1 :(得分:1)

作为Tom的答案的附加组件,我建议存储IndexPath而不是Int还添加

var lastCheckedRow:IndexPath = IndexPath(row: 0, section: 0)

这允许您仅重新加载新检查的行和先前检查的行而不是整个表视图,并且它也将支持多个部分。在您当前只有3行的阶段并不重要,但对于更大的表视图,这将更有效。它还消除了UITableView.reloadData()的闪烁效果 代码类似于:

//0 based on assumption that first cell is checked by default
var checkedRow:IndexPath = IndexPath(row: 0, section: 0)
var lastCheckedRow:IndexPath = IndexPath(row: 0, section: 0)

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //Update checkedRow for reload but keep track of current tick
    lastCheckedRow = checkedRow
    checkedRow = indexPath

    //Remove previous tick
    tableView.reloadRows(at: [lastCheckedRow], with: .automatic)

    //Update new tick
    tableView.reloadRows(at: [checkedRow], with: .automatic)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ViewCell
    if indexPath.row == checkedRow {
        cell.suggestionImg.image = UIImage(named: "tick.png")
    } else {
        cell.suggestionImg.image = UIImage(named "untick.png")
    }
    return cell
}

通过更改我使用with:UITableViewRowAnimation示例的.automatic参数,您还可以在勾选不同单元格时创建理想的视觉效果。

答案 2 :(得分:0)

allowsMultipleSelection:最简单的事情可以帮到你。 在设置viewDidLoad

后,在tableView中添加以下行
override func viewDidLoad() {

    // ... setup you need

    tableView.allowsMultipleSelection = false

}

希望这有帮助!