gpt4 book ai didi

swift - 跨 .swift 文件传输用户默认值

转载 作者:行者123 更新时间:2023-11-28 14:41:09 24 4
gpt4 key购买 nike

我想在应用程序实用程序文件中设置用户默认值,并在我想要的任何 View Controller 中调用它们。这是今天的小部件:

import UIKit
import NotificationCenter

class TodayViewController: UIViewController, NCWidgetProviding {

@IBOutlet weak var BitCount: UILabel!
@IBOutlet weak var upCost: UILabel!

var Bits:Double = defualts.double(forKey: "bits")
var bitsPerClick:Double = defualts.double(forKey: "bitsPerClick")
var upgradePrice:Double = defualts.double(forKey: "upgradeCost")

//Click bit
@IBAction func Click(_ sender: Any) {
AppUtility().bitClick()
BitCount.text = "\(Bits)"
}

//Click Upgrade
@IBAction func Upgrade(_ sender: Any) {
AppUtility().upgradeClick()
upCost.text = "Cost \(upgradePrice)"
BitCount.text = "\(Bits)"
}

这是应用实用程序:

import Foundation
import UIKit

let defualts = UserDefaults.standard

var Bits:Double = defualts.double(forKey: "bits")
var bitsPerClick:Double = defualts.double(forKey: "bitsPerClick")
var upgradePrice:Double = defualts.double(forKey: "upgradeCost")

class AppUtility: UIViewController {

public func setDefualts() {
defualts.set(0, forKey: "bits")

defualts.set(1, forKey: "bitsPerClick")

defualts.set(10, forKey: "upgradeCost")
}

public func upgradeClick() {

if Bits >= upgradePrice {
Bits = Bits - upgradePrice
bitsPerClick = bitsPerClick + 1
upgradePrice = upgradePrice * 1.5
}
}
public func bitClick() {
Bits = Bits + bitsPerClick
}
}

当我运行代码时,我的所有标签都显示为空白,因此我假设用户默认值未设置或未正确调用

最佳答案

您将值存储为整数,但将它们读取为 double 值。

改变

 defualts.set(1, forKey: "bitsPerClick")

 defualts.set(1.0, forKey: "bitsPerClick")

将它们读作整数

var bitsPerClick:Int = defualts.integer(forKey: "bitsPerClick")

关于swift - 跨 .swift 文件传输用户默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50520805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com