samedi 2 avril 2016

Uncheck UITableview custom checkbox option in Swift

I am trying to make a custom checkbox list using the UITableview that allows single selections (I should however be able to select as many options as I want) and a custom UITableCell.

My custom cell contains a Label and an ImageView and all I want is to change the image contained in the IV on tap.

I am able to change the image from unchecked to checked in my didSelectRowAtIndexPath without a problem but I am having problems changing it back from checked to unchecked.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    print("tableView -> didSelectRowAtIndexPath")

    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CustomCellVC

    cell.backgroundColor = UIColor.clearColor()
    cell.ivRiskCellImage.image = UIImage(named: "CheckedBox")
}

I tried to play with the highlighted state of the ImageView by adding the checkedbox image as the highlighted image and then turning it on and off but it only enters the if but ignores the if else if clicked again

    if(cell.ivCellImage.highlighted == false)
    {
        print("Highligth is OFF")
        cell.ivCellImage.highlighted = true
    }
    else if(cell.ivCellImage.highlighted == true)
    {
        print("Highligth is ON")
        cell.ivCellImage.highlighted = false
    }

as well as checking what image is inside the IV, this if-else block being completely ignored

    if(cell.ivRiskCellImage.image!.isEqual(UIImage(named: "UncheckedBox")))
    {
        print("Is unchecked!")
        cell.ivRiskCellImage.image = UIImage(named: "CheckedBox")
    }
    else if(cell.ivRiskCellImage.image!.isEqual(UIImage(named: "CheckedBox")))
    {
        print("Is checked!")
        cell.ivRiskCellImage.image = UIImage(named: "UnheckedBox")
    }

Moreover, when I manage to display the checkedbox image on click I get something like this

enter image description here

while if I try setting the checked box for all the cells in cellForRowAtIndexPath by adding this

cell.ivRiskCellImage.image = UIImage(named: "CheckedBox")

the checkbox tick is no longer semitransparent but white, as it should be

enter image description here

Any ideas? I spent quite some time trying to solve this without any luck.




Aucun commentaire:

Enregistrer un commentaire