Zim
Zim

Reputation: 722

Swift selector method not being called

I create an action class to store the selectors, then addTarget to the button, but when I click it, the method in the action class has not been called

class ItemCardAction {
    
    static var shared: ItemCardAction = ItemCardAction()
    
    private init() {
       
    }
    
    var action: Selector = #selector(ItemCardAction.shared.buttonPressed)

    @objc func buttonPressed(_ sender: UIButton!) {
        print("TEST")
        AppEngine.shared.updateItem(tag: sender.tag)
        AppEngine.shared.notigyAllObservers()
        //self.updateUI()
    }
}

add target

button.addTarget(self, action: ItemCardAction.shared.action, for: .touchDown)

Upvotes: 0

Views: 848

Answers (1)

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20369

What you need is

button.addTarget(ItemCardAction.shared, action: ItemCardAction.shared.action, for: .touchUpInside)

If you look at addTarget method carefully, the first argument is target, when button receives (in this specific case) a touch inside event, iOS will look for the specified selector (specified in action parameter) in target specified. In your case you specified the target as self and clearly selector is not available in self's scope hence nothing happens :)

Upvotes: 1

Related Questions