Disable button for some time

Hello there, if somebody would ask me what I hate the most, is Timer. I’ve done some hard things, from my perspective, but using Timer and all its functions is driving me up the wall.

Does anyone have an idea about how can I disable a button for a specific time? Thanks in advance…

Timers are a bit of a hassle if you aren’t familiar with them.

Are you using UIKIt or SwiftUI?

Im kinda new and don’t completely know what you are trying to do but I made this code work. Maybe you can play with it to get it to work for what you need.

import SwiftUI

struct ContentView: View {
 
    @State private var buttonDisabled = true
    
    var body: some View {
        
        Button(action: {
           
        }, label: {
            Text(buttonDisabled ? "Disabled" : "Click Me")
                .frame(width: 200, height: 100)
                .padding()
                .foregroundColor(.white)
                .background(Color.blue)
        })
        .disabled(buttonDisabled == true)
        .onAppear {
            DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                buttonDisabled = false
            }
        }
    }
}

Essentially what happens is the button is disabled while buttonDisabled is true. When the view is loaded 5 seconds later buttonDisabled is false.

1 Like

Good suggestion Scott.

Another version… every time the button is re-enabled when the time elapses, you can tap it again.

struct ContentView: View {

    @State private var buttonDisabled = false

    var body: some View {

        Button(action: {
            buttonDisabled = true
            DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                buttonDisabled = false
            }
        }, label: {
            Text(buttonDisabled ? "Disabled" : "Click Me")
                .frame(width: 200, height: 100)
                .padding()
                .foregroundColor(.white)
                .background(Color.blue)
        })
        .disabled(buttonDisabled)
    }
}
2 Likes

Oh nice! I didn’t even think about putting DispatchQueue in the action code. Im going to save that in my snippets for future use lol.

2 Likes

SwiftUiI for the current view I want to do that

Is the delay intended to always be a fixed value?

Thank you, it was really helpful !

Thank you, it was really helpful:)

1 Like