首页 > 解决方案 > 滚动表格视图上的重复复选标记

问题描述

我有一个tableView包含自定义标签和按钮(设置复选标记图像)。我可以从数组中正确获取标签的所有文本。但是选择时的按钮(选中/未选中的图像)显示复选标记,但它在滚动时消失并显示在另一个单元格上。单元格正在被重复使用,但我无法获得单独的选择和正确的结果。重复发生在滚动tableView。而且数组也没有附加正确的选择结果。

下面是代码。

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

    let cell = tvSelectGroup.dequeueReusableCell(withIdentifier: "cellnewgroup")

    let device = userDeviceArray[(indexPath as NSIndexPath).row]
    cell?.layer.cornerRadius = 10
     cell.slider.tag = indexPath.row
     if arraySensitivity.count==0
     {
     }else
     {
        cell.slider.value = Float(arraySensitivity[indexPath.row])
      }
    if let lbl = cell?.contentView.viewWithTag(1) as? UILabel
    {
        lbl.text = device
        lbl.textColor = UIColor.white
    }

    if let btnChk = cell?.contentView.viewWithTag(2) as? UIButton
    {
        print("button...")
        btnChk.addTarget(self, action: #selector(checkboxClicked(_ :)), for: .touchUpInside)
        if btnChk.currentImage==#imageLiteral(resourceName: "Checkmark")
        {
            addDeviceInArray(cell: cell!)
        }
    }
    print("arr\(arr)")
    return cell!
}

@objc func checkboxClicked(_ sender: UIButton)
{
    print("checked..")
    sender.isSelected = !sender.isSelected
}

@objc func addDeviceInArray(cell:UITableViewCell)
{
    let lbl = cell.contentView.viewWithTag(1) as? UILabel
    if !arr.contains((lbl?.text)!)
    {
        arr.append((lbl?.text)!)
        print("array in label\(arr)")
    }
}

标签: iosswiftuitableviewcheckbox

解决方案


  1. 创建状态数组 - 假/真。基于单元格或任何内容项的更改状态。
  2. 创建您的自定义单元格
  3. 按下按钮时在单元格内添加处理程序

例如:

var states: [Bool] = [true, true, false]
var deviceName[String] = ["PC", "Mac", "iPhone"]

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

let cell = tableView.dequeueReusableCell(withIdentifier: "cellnewgroup") as? MyCell

let device = deviceName[indexPath.row]
cell?.layer.cornerRadius = 10

if state[indexPath.row] {
   cell.button.setImage("uncheckmark")

} else {
  cell.button.setImage("checkmark")
}


cell.onClick = {

  state[indexPath.row] != state[indexPath.row]

}

if states[indexPath.row] {
    lbl.text = device
    lbl.textColor = UIColor.white
} else  { // remove this
    // print("button...")

// add button to cell class and use it.
   //print("arr\(arr)")
   //return cell!
}


class MyCell: UITableViewCell {

    @IBOutlet var button: UIButton // connect to storyboard or create your own
    var onClick: () -> Void = {}



    // add this method to your cell, connect to storyboard or create your own target
    @IBAction func checkboxClicked(sender: UIButton) {

         onClick()

    }
}

推荐阅读