我按钮的作用是按下它后会在当天余下时间禁用。现在我的代码在按下后会禁用它,但是如果用户离开应用程序并返回它,则该按钮将再次启用。有没有办法使用NSUserDefaults?
let save = UserDefaults.standard
let calendar = Calendar.current
let now = Date()
这是在viewDidLoad:
中 let seven_today = calendar.date(
bySettingHour: 7,
minute: 0,
second: 0,
of: now)!
let two_thirty_today = calendar.date(
bySettingHour: 14,
minute: 30,
second: 0,
of: now)!
if now >= seven_today && now <= two_thirty_today
{
getPointsOutlet.isEnabled = true
}
else
{
getPointsOutlet.isEnabled = false
}
这是按下按钮的功能:
Total_Points += 12
pointsLabel.text = "Total Points: \(Total_Points)"
getPointsOutlet.isEnabled = false
答案 0 :(得分:1)
试试这个:
if now >= seven_today && now <= two_thirty_today
{
let savedDayNum = defaults.integer(forKey: "dayClickNum")
let date = Date()
let calendar = Calendar.current
let nowDayNum = calendar.component(.day, from: date)
if(savedDayNum == nowDayNum)
{
getPointsOutlet.isEnabled = false
}
else
{
getPointsOutlet.isEnabled = true
}
}
else
{
getPointsOutlet.isEnabled = false
}
//在函数中单击执行此操作
Total_Points += 12
pointsLabel.text = "Total Points: \(Total_Points)"
getPointsOutlet.isEnabled = false
let date = Date()
let calendar = Calendar.current
let dayOfClickDate = calendar.component(.day, from: date)
defaults.set(dayOfClickDate, forKey: "dayClickNum")
另外,对于一个完美的解决方案,你可以照顾一个月,因为如果存储的num天与另一个月的开放日重合,用户可能无法再启动app一个月可能会禁用该按钮