gpt4 book ai didi

ios - Swift 4 : Checking if week, 月、2 个月等自使用日历首次启动以来已过去

转载 作者:行者123 更新时间:2023-11-28 11:35:47 25 4
gpt4 key购买 nike

我正在尝试添加计时器,以便在应用程序的初始启动日期之后的一周、一个月、两个月等时间出现一个按钮。

我用过 Date.addingTimeInterval (见下面的代码),但它似乎在较长时间(周/月)内效果不佳。 Swift 文档建议使用日历,但我不确定该怎么做。

override func viewDidLoad() {
super.viewDidLoad()

if installedDate == nil {
installedDate = Date()
let timer = Calendar.current

Button1.isHidden = true
Button2.isHidden = true
Button3.isHidden = true
}

else {
print("Not first run")
print(installedDate!)

let Button1Date = Date().addingTimeInterval(604800) //for after 1 week
let Button2Date = Date().addingTimeInterval(2592000) //for after 1 month
let Button3Date = Date().addingTimeInterval(5184000) //for after 2 months


if installedDate == Button1Date {
Button1.isHidden = false
}
if installedDate == Button2Date {
Button2.isHidden = false
}
if installedDate == Button3Date {
Button.isHidden = false
}

}

}

var installedDate: Date? {
get {
return UserDefaults.standard.object(forKey: "installedDateKey") as? Date
}
set {
UserDefaults.standard.set(newValue, forKey: "installedDateKey")
}
}

将发布日期与我需要的预期日期进行比较的更有效方法是什么?

最佳答案

根据我对您问题的理解,如果他们使用该应用程序超过一定时间,您希望显示一个按钮。如果是这样,我已经编写了一些对您有帮助的代码:

let timeSinceInstalled = -(installedDate ?? Date()).timeIntervalSinceNow

Button1.isHidden = timeSinceInstalled < 604800
Button2.isHidden = timeSinceInstalled < 2592000
Button3.isHidden = timeSinceInstalled < 5184000

您实际上可以替换 viewDidLoad() 函数中的大部分代码,甚至是检查 installedDate == nil 的部分。这是您更新后的代码:

override func viewDidLoad() {
super.viewDidLoad()
let timeSinceInstalled = -(installedDate ?? Date()).timeIntervalSinceNow
Button1.isHidden = timeSinceInstalled < 604800
Button2.isHidden = timeSinceInstalled < 2592000
Button3.isHidden = timeSinceInstalled < 5184000
}

var installedDate: Date? {
get {
return UserDefaults.standard.object(forKey: "installedDateKey") as? Date
}
set {
UserDefaults.standard.set(newValue, forKey: "installedDateKey")
}
}

如果您想在按钮不可点击时将标题设置为“您没有可用的”,请使用以下代码:

override func viewDidLoad() {
super.viewDidLoad()
let timeSinceInstalled = -(installedDate ?? Date()).timeIntervalSinceNow
setTitle(Button1, timeSinceInstalled < 604800)
setTitle(Button2, timeSinceInstalled < 2592000)
setTitle(Button3, timeSinceInstalled < 5184000)
}

func setTitle(_ button: UIButton, _ statement: Bool) {
button.setTitle(statement ? "You have none available" : "Click me", for: .normal)
button.isEnabled = !statement
}

var installedDate: Date? {
get {
return UserDefaults.standard.object(forKey: "installedDateKey") as? Date
}
set {
UserDefaults.standard.set(newValue, forKey: "installedDateKey")
}
}

关于ios - Swift 4 : Checking if week, 月、2 个月等自使用日历首次启动以来已过去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55465662/

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