【问题标题】:Selector to Static Func with Parameters in Swift?Swift 中带参数的静态函数的选择器?
【发布时间】:2018-02-06 17:45:04
【问题描述】:

在 Swift 中是否可以有一个带参数的静态函数的选择器?

我尝试的语法是这样的:

  button.addTarget(VCPresenter.self, action: #selector(VCPresenter.handleBackButton(_:parentNavigationController!)), for: .touchUpInside)

静态方法是这样的

  @objc public static func handleBackButton(_ controller: UINavigationController) {
    controller.popViewController(animated: true);
}

当我编译时,我得到

错误:'#selector' 的(24, 56) 参数未引用 '@objc' 方法、属性或初始化程序

这有可能吗?

【问题讨论】:

  • 您仍然需要一个NSObject 子类实例作为目标参数(可能是一个共享类),选择器确实可以表示一个静态方法。

标签: swift function swift3 selector


【解决方案1】:

我用单视图应用程序和这项工作制作了新项目。让我知道这是否适合您。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let button = UIButton()
        button.addTarget(self, action: #selector(ViewController.buttonAction(x:y:)), for: .touchUpInside)
    }

    @objc public static func buttonAction(x: Int, y: String){
        print("Test")
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 2018-06-23
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    相关资源
    最近更新 更多