I am trying to change my "selected" variable so that when a character cell in the collectionview is selected, the view controller can be dismissed when the user clicks the button (sendTapped). However, it is not changing the variable value back to false when the user deselects a cell, so the view controller is dismissed when the user deselects a cell and then clicks the button.
class CharactersViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let characters = [...]
let characterImages = [...]
var selectedIndex: Int?
var selected = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func sendTapped(_ sender: Any) {
***if selected {
self.dismiss(animated: true, completion: nil)
let initialViewController = UIStoryboard.initialViewController(for: .main)
self.view.window?.rootViewController = initialViewController
self.view.window?.makeKeyAndVisible()
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.characters.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CharacterViewCell
cell.characterImage.image = UIImage(named: characterImages[indexPath.row])
if selectedIndex == indexPath.row {
cell.contentView.layer.borderColor = UIColor.yellow.cgColor
cell.contentView.layer.borderWidth = 2.0
}else{
cell.contentView.layer.borderColor = UIColor.clear.cgColor
cell.contentView.layer.borderWidth = 1.0
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let character = characters[indexPath.row]
***selected = true
selectedIndex = selectedIndex == indexPath.row ? nil : indexPath.row
ProfileService.updateChild(child: "char", childVal: character)
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
***selected = false
}
}