I am trying to get this done. I want a button, that gets disabled once it is pressed for a certain amount of time. And once that time is over, the button is enabled again until it is pressed again, which then disables it for set time. I do not want the button to be enabled again easily by restarting the app. It has to stay disabled until the time is over and not until the next launch of the app .. so far my code is only working to disable the button once. It is not working, to enable it again after the time has passed. also the button is enabled again right after I relaunch the app. That is not supposed to happen.
Anyone have an idea, how I can get it working the way I want it to?
This is the code I have:
button.isUserInteractionEnabled = false
Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { _ in
button.isUserInteractionEnabled = false
})
I have also tried it this way:
_ = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)
_ = Timer.scheduledTimer(timeInterval: 0.0, target: self, selector: #selector(fireTimer2), userInfo: nil, repeats: false)
with the @objc being:
@objc func fireTimer() {
print("Timer fired!")
}
@objc func fireTimer2() {
print("Start timer.")
}
With this I wanted to try, if I can set a start time and a repeating time in the hopes to get things going with the button. I did not. Can anyone help me?
Appreciate it a lot! All the best
UPDATE, June 29:
This here is the code, I use for my button and to make the disable/enable function, that I want, work.
@objc private let actionButton: UIButton = {
let button = UIButton()
button.setTitle("Button Title", for: .normal)
button.titleLabel?.font = UIFont(name: "Times New Roman", size: 16)
button.setTitleColor(.secondaryLabel, for: .normal)
button.addTarget(self, action: #selector(didTapButton), for: .touchDown)
return button
}()
@objc func didTapButton() {
self.actionButton.isUserInteractionEnabled = false
Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { _ in
self.actionButton.isUserInteractionEnabled = true
}}
So how do I store the data from the timer in the core data(???) or UserDefaults(???) or where ever, so the timer doesnt reset when relaunching the app?