取消选择集合视图单元格不会更改变量值

时间:2019-03-27 00:49:52

标签: swift select indexing collectionview deselect

我试图更改我的“ selected”变量,以便在选择collectionview中的字符单元格时,当用户单击按钮(sendTapped)时可以关闭视图控制器。但是,当用户取消选择一个单元格时,并没有将变量值改回false,因此,当用户取消选择某个单元格然后单击按钮时,视图控制器将被关闭。

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
}

}

0 个答案:

没有答案