0

I display a list of users through a UICollectionView (stored in CoreData) Each cell has : - a name (UItextField) - a state (ON / OFF) (bool)

I want to pass my boolean var concerning the user state (ON or OFF) with a UISwitch.

I've correctly set up my collectionview func : identified my cell, displayed the name of user, added a target func for the UISwitch.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: userId, for: indexPath) as! UserCell
    let nameInfos = usersList[indexPath.item]
    cell.usersList = nameInfos
    nameInfos.name = cell.userNameTextField.text
    cell.userNameTextField.delegate = self
    let switchActive = cell.userSwitch

    switchActive.addTarget(self, action: #selector(self.didPlayerActivate(_:)), for: .valueChanged)

    return cell
}

@objc func didPlayerActivate(_ sender : UISwitch){
    sender.isOn ? isActive() : isntActive()
}

// then my 2 func : isActive and isntActive

My question is how to set each user ON or OFF with my "didPlayerActivate" func. I thought about selecting the right indexPath with the UISwitch, but I don't know how to do this.

Creanomy
  • 216
  • 2
  • 12
  • Here’s the same issue with buttons instead of switches https://stackoverflow.com/q/28659845/1630618 – vacawama Jul 21 '19 at 12:12
  • 1
    In particular, [Paulw11’s answer](https://stackoverflow.com/a/38941510/1630618) is a clean way to handle it. – vacawama Jul 21 '19 at 12:20
  • Thanks @vacawama, I thought about this solution I've seen before. But, for the moment, it just crashs my app : `Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: [MyApp.MySwitch _layoutAttributes]: unrecognized selector sent to instance 0x7fc6b1ebba00'` – Creanomy Jul 22 '19 at 07:21
  • The delegate method seems to be a good solution, but still impossible to reach indexPath : each time I try to guard let my indexPath, it crashes, even when I return nil... – Creanomy Jul 22 '19 at 10:12
  • Finally, I used closures and it works fine ! Protocol / delegate is not made for UISwitch. Anyway @vacawama, thanks for your help. – Creanomy Jul 24 '19 at 09:44

1 Answers1

0

EDIT : it seems that protocol and delegate method is not made for UISwitch, as said @Daniel here : https://stackoverflow.com/a/32587078/8162027. I succeeded with using closure like this : in my cell :

var mySwitchAction : (()->())?
@objc func switchValueChanged(_ sender: UISwitch) {
    self.switchAction?()
}
mySwitch.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)

in my CollectionView :

cell.switchAction = {
        () in
        print("it works")
    }
Creanomy
  • 216
  • 2
  • 12