【问题标题】:Swift selector method not being called未调用 Swift 选择器方法
【发布时间】:2021-02-17 06:49:59
【问题描述】:

我创建了一个action类来存储选择器,然后addTarget到按钮,但是当我点击的时候,action类中的方法并没有被调用

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()
    }
}

添加目标

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

【问题讨论】:

  • 而不是self,尝试使用ItemCardAction.shared作为目标。

标签: objective-c swift uibutton action selector


【解决方案1】:

你需要的是

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

如果你仔细看addTarget方法,第一个参数是target,当按钮接收到(在这种特定情况下)touch inside事件时,iOS会在指定的target中寻找指定的选择器(在action参数中指定)。在您的情况下,您将目标指定为 self 并且显然选择器在 self 的范围内不可用,因此没有任何反应:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多