I have a custom class of UIButton. I want to add delay on action if user tap on button. I can use following code to each and every button action but I want to use generic solution so that I need not to visit each and every button action places.
@IBAction func buttonTapped(_ sender: CustomButton) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4, execute: {
// do action
})
}
2
Answers
You can pass the action in to the custom class as a closure. You then just need to link the IBAction up in storyboard or you can do programatically in the button init with addTarget if not using storyboard. I assume you have an init in your custom class setting up other properties on the button.
Calling programatically you can pass the action in as a closure as follows. Be wary if you are running logic that may capture the view controller self and use weak or unowned if actions could run a more than a short response in async.
A rather generic way is to use Combine.
Implement an extension of
UIControl
described in the Medium article Observe UIButton Events Using Combine in Swift 5 to be able to observe any button event, the full code is available on GitHub.Add this extension of
UIButton
, thedelay
operator does what its name implies.Observe the button(s)