在所有单元格UICollectionView中增加,更新和保存分数

时间:2017-11-22 16:40:28

标签: ios swift uicollectionview cell

我正在使用Swift 4创建单词益智游戏,并且我有300个单元格,如何在所有单元格UICollectionView中增加,更新和保存分数?

代码:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


    if indexPath.row + 1 < EnabledID {

        cell.backgroundView = UIImageView(image: UIImage(named: "CorrectMark"))
        cell.isUserInteractionEnabled = false
        cell.cellLabel.text = ""
        QV.score += 2
        QV.lblScoreCoins.text = String(score)
        UserDefaults.standard.set(lblScoreCoins.text, forKey: "Key")
        UserDefaults.standard.synchronize()
        lblScoreCoins.text = UserDefaults.standard.string(forKey: "Key")

    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let QV : QuestionView = self.storyboard?.instantiateViewController(withIdentifier: "QuestionView") as! QuestionView
    QV.idFromCollection = indexPath.row + 1

    self.present(QV, animated: true, completion: nil)

    QV.lblScoreCoins.text = UserDefaults.standard.string(forKey: "Key")


}

1 个答案:

答案 0 :(得分:-1)

我找到了一个解决方案,在ViewController类中编写这段代码:

override func viewDidLoad() {
    super.viewDidLoad()

    let score = UserDefaults.standard.integer(forKey: "ScoreCoins")
    lblScoreCoins.text = String(score)

}

func addScore() {

    var score = UserDefaults.standard.integer(forKey: "ScoreCoins")
    score += 1
    UserDefaults.standard.set(score, forKey: "ScoreCoins")
    lblScoreCoins.text = String(score)

}