'Weird addAction & addTarget behaivor dfiference for UIButton in a CollectionViewCell
I have a button in a UICollectionViewCell. I added a touch action to the button for nofitying the ViewController. When I use addAction(_ action: UIAction, for controlEvents: UIControl.Event) method for notifying the ViewController, the action handler gets called multiple times (usually twice).
But if I use addTarget(_ target: Any?, action: Selector, for controlEvents: UIControl.Event) method, the selector gets called single time which is what I want.
Here is the sample code of my problem:
private let button = UIButton()
init() {
...
configure()
}
private func configure() {
...
button.addTarget(self, action: #selector(buttonSelector), for: .primaryActionTriggered)
button.addAction(UIAction { [unowned self] _ in
// Gets called multiple times
}, for: .primaryActionTriggered)
...
}
@objc private func buttonSelector() {
// Gets called single time
}
I really don't understand what's going on here. I tought the addAction method is a modern way of addTarget method. Why do these have different behaivors in this situation?
And why the addAction handler gets called multiple times in the first place? Is there something I am missing? There should be some UICollectionViewCell related problems here I presume.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
