从 UserDefaults 值增加 UILabel - Swift

Increment UILabel from UserDefaults value - Swift

我正在创建一个计数器,并且希望能够在每次按下按钮时增加 1,这会更新我的 UILabel 并保存到 UserDefaults。我能够很好地保存和检索值,但是当我再次按下按钮时,数字又回到了一个。

这是我的代码

override func viewDidLoad() {
        super.viewDidLoad()
        if let save = UserDefaults.standard.object(forKey: "points1") as? String
        {
            teamOnePoint.text = save
            print(save)
        }

        // Do any additional setup after loading the view.
    }


    @IBAction func teamOneButtonPressed(_ sender: Any) {
        pointScore1 += 1
        teamOnePoint.text = "\(pointScore1)"
        UserDefaults.standard.set(teamOnePoint.text, forKey: "points1")

    }

您从未将 pointScore1 设置为从 UserDefaults 检索到的值。

首先检索并存储 Int 值,而不是 String

override func viewDidLoad() {
    super.viewDidLoad()

    pointScore1 = UserDefaults.standard.integer(forKey: "points1")
    teamOnePoint.text = "\(pointScore1)"
}

@IBAction func teamOneButtonPressed(_ sender: Any) {
    pointScore1 += 1
    teamOnePoint.text = "\(pointScore1)"
    UserDefaults.standard.set(pointScore1, forKey: "points1")
}

请注意,在全新安装应用后,初始值将为 0。按需要处理。

 override func viewDidLoad()
{
    super.viewDidLoad()

    if let save = UserDefaults.standard.object(forKey: "points1") as? String
    {
         print(save)
    }
}

@IBAction func btnIncrTap(_ sender: Any)
{
    pointScore1 += 1
    UserDefaults.standard.set(pointScore1, forKey: "points1")
    print(String(describing: UserDefaults.standard.object(forKey: "points1")))
}