如何在 swift 的背景中禁用按钮,即使它不是 运行?

How to disable a button even when it is not running in the background in swift?

当我在后台说不是 运行 时,我的意思是当用户双击他们的主页按钮并向上滑动时,该按钮将重新启用

这是我viewDidLoad

中的代码
if let waitingDate:Date = UserDefaults.standard.value(forKey: "waitingDate") as? Date
    {
        let currentDate = Date()

        if(currentDate.compare(waitingDate) == ComparisonResult.orderedDescending)
        {
            getPointsOutlet.isEnabled = true
        }
    }

这是@IBAction func

中的代码
getPointsOutlet.isEnabled = false

let newDate = Calendar.current.date(byAdding: .day, value: 1, to: Date())

UserDefaults.standard.setValue(newDate, forKey: "waitingDate")

保存:

UserDefaults.standard.set(Date(), forKey:"date")
UserDefaults.standard.synchronize()

检索:

if let dateValue = clickdate.object(forKey: "date") as? Date{
    ...
}

要在 24 小时后启用按钮,请检查此 post:

如果您想将按钮禁用 24 小时,请保存明天的日期:

let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())
UserDefaults.standard.set(tomorrow, forKey:"date")

正在检查是否应启用该按钮:

let currentDate = Date()

if(currentDate.compare(dateValue) == ComparisonResult.orderedDescending){
    //reenable button
}

要获取值,请始终检查使用 guard 或 if let 语句以防止崩溃:-

//Set value in user default 
UserDefaults.standard.set(Date(), forKey:"date")
UserDefaults.standard.synchronize()

//Get value from user default 
guard let value = UserDefaults.standard.object(forKey: "date") as? Date else {return}
print(value)