Swift 为什么我会收到错误消息;无法识别的选择器“;在我的Xcode调试控制台中

Swift 为什么我会收到错误消息;无法识别的选择器“;在我的Xcode调试控制台中,swift,xcode,uibutton,selector,Swift,Xcode,Uibutton,Selector,我在Swift项目中有一个创建自定义按钮的函数,在该项目中,我传递了一个objc函数选择器名称,但当我单击按钮时,代码崩溃。有人能指出我的代码崩溃的原因吗?我收到错误消息: 无法识别的选择器+[TwitterTutorial.Utilities在SaveAnAccountButtonClicked上处理] 以下是我的自定义按钮功能: class Utilities { static func createCustomButton(withFirstPart first: String,

我在Swift项目中有一个创建自定义按钮的函数,在该项目中,我传递了一个objc函数选择器名称,但当我单击按钮时,代码崩溃。有人能指出我的代码崩溃的原因吗?我收到错误消息:
无法识别的选择器+[TwitterTutorial.Utilities在SaveAnAccountButtonClicked上处理]

以下是我的自定义按钮功能:

class Utilities {

    static func createCustomButton(withFirstPart first: String, andSecondPart second: String, andSelector selector: Selector) -> UIButton {
        let button = UIButton(type: .system)
        
        let attributedTitle = NSMutableAttributedString(string: first,
                                                        attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16),
                                                                     NSAttributedString.Key.foregroundColor: UIColor.white])
        attributedTitle.append(NSAttributedString(string: second,
                                                  attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16),
                                                               NSAttributedString.Key.foregroundColor: UIColor.white]))
        
        button.setAttributedTitle(attributedTitle, for: .normal)
        
        button.addTarget(self, action: selector, for: .touchUpInside)

        return button
    }
}
下面是对创建按钮的函数的调用:

    private let dontHaveAccountButton = Utilities.createCustomButton(withFirstPart: "Don't have an account? ",
                                                                     andSecondPart: "Sign Up",
                                                                     andSelector: #selector(handleDontHaveAnAccountButtonClicked))

    @objc func handleDontHaveAnAccountButtonClicked() {
        print("DEBUG: Don't have an account button clicked")
    }

我注意到,当我从类方法声明中删除static关键字时,它会起作用,但我希望在类实用程序中使用静态方法。

您将
目标设置为
self
,这意味着必须在
实用程序中声明选择器方法

可能的解决办法是

  • 向方法中添加参数
    target
  • 扩展
    ui按钮
  • 扩展
    UIViewController
    或创建按钮的类型
  • 实用程序中声明选择器方法(没有多大意义)
您正在使用静态函数创建按钮,并且在调用

button.addTarget(self, action: selector, for: .touchUpInside)
self
引用的是类
Utilities
而不是实例

因此,选择器还应引用类(例如静态)函数,如

@objc static func handleDontHaveAnAccountButtonClicked() {
    print("DEBUG: Don't have an account button clicked")
}

谢谢,我为这个建议为targetHanks添加了一个额外的参数,但是我的代码仍然崩溃,错误与以前相同。但是,当我传递目标并使用它在button.addTarget()方法中设置目标时,它会工作。