Search code examples
swiftuiswitchcollectionview

How to bind Switch state to an object in Swift?


In my app I have a switch and I want it to be an indicator for saving images. For now I have just a button that saves all the images.

enter image description here

It just makes more sense with an example

What I've tried:

func saveTapped() {

let cell = collectionView?.cellForItem(at: indexPath) as! CustomCell

for image in images where cell.savingSwitch.isOn  {

...

But I can't access indexPath. How should I call this Save method in order to access a particular row in my collectionView? Or is there another way?


Solution

  • First, you'll need a way to store the "save" settings alongside each image in your table, e.g. by keeping the image and the flag in a struct:

    struct TableEntry {
       let image: UIImage
       var save = false
    }
    

    and use a var images: [TableEntry] in the data source of your tableview.

    You can then use the tag property of each UISwitch to store the row it's in, e.g. in

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(...)
        cell.switch.tag = indexPath.row
        cell.switch.isOn = self.images[indexPath.row].save
        cell.imageView.image = self.images[indexPath.row].image
        return cell
    }
    

    and then use the tag in the method that's called when the switch value changes to know which image is being referred to:

    @IBAction func switchChanged(_ sender: UISwitch) {
        self.images[sender.tag].save = sender.isOn
    }
    
    func saveTapped() {
        let imagesToSave = self.images.filter { $0.save }
    }