【问题标题】:Why UIButton removeTarget:action:forControlEvents: has removed all targets?为什么 UIButton removeTarget:action:forControlEvents: 已删除所有目标?
【发布时间】:2017-04-13 05:31:48
【问题描述】:

我已将多个目标添加到 UIButton。我想删除其中一个目标,但在 removeTarget:action:forControlEvents: 之后得到了 nil。

import UIKit

class IndexViewController: UIViewController {
    lazy var sndBtn = UIButton(type: .system)

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        view.addSubview(sndBtn)
        sndBtn.setTitle("Hi", for: .normal)

        sndBtn.addTarget(self, action: #selector(IndexViewController.onClick1(_:)), for: .touchUpInside)
        sndBtn.addTarget(self, action: #selector(IndexViewController.onClick2(_:)), for: .touchUpInside)
        print(sndBtn.actions(forTarget: self, forControlEvent: .touchUpInside) as Any)

        sndBtn.removeTarget(self, action: #selector(IndexViewController.onClick1(_:)), for: .touchUpInside)
        print(sndBtn.actions(forTarget: self, forControlEvent: .touchUpInside) as Any)
    }

    @objc
    func onClick1(_ btn: UIButton) {
        print("Method1")
    }

    @objc
    func onClick2(_ btn: UIButton) {
        print("Method2")
    }
}

结果只是显示:

Optional(["onClick1:", "onClick2:"])

nil

【问题讨论】:

  • @Pang 感谢您的回复,我认为 Aleksandr 已经解决了这个问题。 “如果您在目标参数中指定了一个有效对象,此方法将停止将指定事件传递给与该对象关联的所有操作方法。” - 苹果文档

标签: ios swift3 uibutton


【解决方案1】:

根据Apple Docs

停止传递事件时不考虑 action 参数

【讨论】:

  • 多么奇怪的 API 设计。
猜你喜欢
  • 2011-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-16
  • 1970-01-01
相关资源
最近更新 更多