基于SwiftUI中的日期重新启用按钮

dgiusagp  于 5个月前  发布在  Swift
关注(0)|答案(1)|浏览(57)

我正在建立一个习惯跟踪器的过程中,我遇到了一个问题。在我的应用程序中有一个按钮,你可以点击它来表示你已经完成了你的任务。只要按下这个按钮,我把它设置为.disabled()这样任务就不能执行多次。现在我希望每天都能再次按下按钮。如何确保按钮已启用再次在0点钟?我试图改变变量isButtonDisabled在0:00,但没有成功。任何帮助是感激!

import SwiftUI

struct HabitButton: View {
    @State private var isButtonDisabled: Bool = false // This value should change every new day at 0 o'clock.
    @AppStorage("streak") private var streak: Int = 0
    
    var body: some View {
        if (isButtonDisabled == false) {
            Button {
                UNUserNotificationCenter.current().setBadgeCount(0)
                isButtonDisabled = true
            } label: {
                Text("I have eaten an apple")
                    .padding(.vertical, 20)
                    .foregroundStyle(.white)
                    .fontDesign(.rounded)
                    .bold()
                    .frame(width: 400)
            }
            .background(BasicColor.tint)
            .clipShape(RoundedRectangle(cornerRadius: 20))
        } else {
            Button {
                UNUserNotificationCenter.current().setBadgeCount(0)
                isButtonDisabled = true
            } label: {
                Text("I have eaten an apple")
                    .padding(.vertical, 20)
                    .foregroundStyle(.white)
                    .fontDesign(.rounded)
                    .bold()
                    .frame(width: 400)
            }
            .background(BasicColor.tint)
            .clipShape(RoundedRectangle(cornerRadius: 20))
            .disabled(true)
        }
    }
}

#Preview {
    HabitButton()
}

字符串
我尝试了类似的东西,但这些表达式在SwiftUI中是不允许的。

struct HabitButton: View {
    @State private var isButtonDisabled: Bool = false // This value should change every new day at 0 o'clock.
    @AppStorage("streak") private var streak: Int = 0
    
    var body: some View {
        if (Date() == 0) {
            isButtonDisabled = false
        }

r6vfmomb

r6vfmomb1#

用于文件目的

现在我对这个功能做了一点调整,让你一天只能点击一次按钮。为此,我将按钮被点击的日期保存在用户界面中。当应用程序打开时,一个计时器会运行,它每60秒执行一个函数,检查当前日期是否是上次保存日期的后一天。
代码片段:

@AppStorage("lastAppleDate") private var lastAppleDate: Date?

let timer = Timer.publish(every: 60, on: .main, in: .common).autoconnect()

.onReceive(timer) { _ in
        checkIfButtonShouldBeEnabled()
    }

private func checkIfButtonShouldBeEnabled() {
    if let lastAppleDate = lastAppleDate {
        let calendar = Calendar.current
        if !calendar.isDateInToday(lastAppleDate) {
            isButtonDisabled = false
        }
    } else {
        isButtonDisabled = false
    }
}

字符串

相关问题