为什么我在 Xcode 调试控制台中收到错误消息 "unrecognised selector"

Why am I getting the error message "unrecognised selector" in my Xcode debug console

我在我的 Swift 项目中有一个创建自定义按钮的函数,我在其中传递了一个 objc 函数选择器名称,但是当我单击该按钮时代码崩溃了。谁能指出我的代码崩溃的原因?我收到错误消息: Unrecognized selector +[TwitterTutorial.Utilities handleDontHaveAnAccountButtonClicked]

这是我的自定义按钮功能:

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

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

您将 target 设置为 self,这意味着选择器方法必须在 Utilities 中声明。

可能的解决方案是

  • 向方法添加参数 target
  • 扩展 UIButton.
  • 扩展 UIViewController 或创建按钮的类型。
  • Utilities中声明选择器方法(没有多大意义)。

您正在使用 static 函数创建按钮,并且在调用

button.addTarget(self, action: selector, for: .touchUpInside)

self指的是classUtilities不是一个实例。

因此,选择器还应该引用一个class(例如static)函数,比如

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