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

為{幸葍}努か 提交于 2019-12-24 11:11:39

问题


When I say not running in the background, I mean when the user double clicked their home button and swipes up, the button will reenable

This is the code in my viewDidLoad

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

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

This is the code in the @IBAction func

getPointsOutlet.isEnabled = false

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

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

回答1:


To get the value always check use guard or if let statement to prevent the crash:-

//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)



回答2:


Save:

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

Retrieve:

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

For enabling the button after 24 hours check this post: Enabling button after 24 hours

If you want to disable the button for 24 hours then save tomorrow's date:

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

Checking if the button should be enabled:

let currentDate = Date()

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


来源:https://stackoverflow.com/questions/45374975/how-to-disable-a-button-even-when-it-is-not-running-in-the-background-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!