mardi 15 mai 2018

duplicate checkmarks on scrolling tableview

I have a tableview which contains custom label and button(to set checkmark images). I am able get all texts to the label correctly from array.But the button(checked/unchecked images) on selection shows checkmark but it disappears on scrolling and shows on another cell. The cells are getting reused but I am unable to get individual selection and proper result. The duplication happens on scrolling tableview.And also array does not append proper seletecd results.
Below is the code.

 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

    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)")
    }
}




Aucun commentaire:

Enregistrer un commentaire