Search code examples
swiftuiimageviewuiimagecell

How to change an UIImageView into a custom cell


I have an UIImageView in a custom cell (@IBOutlet var imageSquadra: UIImageView!) and in the TableViewController I initialize this imageView:

let squadra = DataManager.sharedInstance.arrayCori[indexPath.row]

        cell.imageSquadra.image = squadra.sfondo1

Now I need to change the image touching up inside the cell with an other image, and return to the previous image touching up into an other cell. Is it hard to do?

EDIT: or if was easier, would be fine apply a CAFilter like a shadow to the image.


Solution

  • On your tableview set multiple selection to NO:

    tableView.allowsMultipleSelection = false
    

    Then you want something like this on your TableViewController

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
       // Store which indexPath has been selected in a global variable
    
       tableView.reloadData()
    }
    
    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.reloadData()
    }
    

    In your cellForRow method you want something like...

    cell.useSelectedImage(indexPath == storedIndexPath)
    

    And finally in your custom cell class you want to add a method that does similar to this

    func useSelectedImage(bool:useSelected)
    {
         self.myImage = useSelected ? "selectedImage" : "unselectedImage"
    }
    

    My Swift is a bit rusty... but you should be able to get the general idea from what I've done here