根据 SwiftUI 中的日期重新启用按钮

问题描述 投票:0回答:1

我正在构建习惯追踪器,但遇到了一个问题。在我的应用程序中,有一个按钮,您可以单击该按钮来指示您已完成任务。一旦按下此按钮,我将其设置为 .disabled(),以便任务不能执行多次。现在我希望每天都能再次按下该按钮。如何确保按钮在 0 点再次启用?我尝试在 0:00 更改变量 isButtonDisabled,但没有成功。如有任何帮助,我们将不胜感激!

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
        }
swift date button swiftui modifier
1个回答
0
投票

用于文档目的

我现在对功能做了一些调整,每天只能点击一次按钮。为此,我将单击按钮的日期保存在 UserDefaults 中。打开应用程序时,计时器会运行,每 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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.