Ask Your Question
1

How can I avoid UIAction being triggered multiple times when a UIButton in a CollectionViewCell is tapped?

asked 2022-06-19 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-10-23 00:00:00 +0000

lalupa gravatar image

One way to avoid UIAction being triggered multiple times when a UIButton in a CollectionViewCell is tapped is by disabling the button until the action is completed. You can use the addTarget method in the cellForRowAtindexPath method to add the target for the button. In the selector method, you can disable the button and then perform the action. Once the action is completed, you can enable the button again. Here's an example:

First, declare a boolean variable:

var buttonIsTapped = false

Next, add the target to the button in cellForRowAtindexPath method:

cell.button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)

In the selector method, disable the button and perform the action:

@objc func buttonTapped(_ sender: UIButton) {
    if !buttonIsTapped {
        buttonIsTapped = true
        sender.isEnabled = false
        //perform action
        sender.isEnabled = true
        buttonIsTapped = false
    }
}

This will ensure that the button is disabled until the action is completed, and will prevent the UIAction from being triggered multiple times.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-19 11:00:00 +0000

Seen: 17 times

Last updated: Oct 23 '22