从UserDefaults值增加UILabel-Swift

时间:2019-03-08 01:47:54

标签: ios swift nsuserdefaults

我正在创建一个计数器,希望每次按下按钮时都可以增加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")

    }

2 个答案:

答案 0 :(得分:1)

您永远不会将=IF(Sheet2!A1="present",0,) =IF(Sheet2!A1="less than 10mins","+1",) =IF(Sheet2!A1="more than 10mins","+2",) =IF(Sheet2!A1="unexcused","+5",) =IF(Sheet2!A1="excused",0,) 设置为从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") } 。根据需要处理。

答案 1 :(得分:-2)

 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")))
}