Swift 4: 在另一个 class 中调用函数时发送到实例的无法识别的选择器

Swift 4: Unrecognized selector sent to instance when calling a function inside another class

对于我的应用程序,我在没有故事板的情况下工作。出于这个原因,我试图通过将更大的函数存储在另一个 class 中并在需要时调用它们来保持我的 ViewController 整洁。

出于某种原因,当我使用#Selector 调用我的函数时,出现崩溃并显示 "Unrecognized selector sent to instance"。

当我将我的函数存储在与#Selector 相同的 ViewController 中时,它工作得很好。

下面的代码有效

视图控制器

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(loginRegisterButton)


}

lazy var loginRegisterButton: UIButton = {
    let button = UIButton(type: .system)
    button.backgroundColor = Color.darkBlue
    button.setTitle("Register", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitleColor(UIColor.white, for: .normal)
    button.layer.cornerRadius = 5
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)

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

    return button
}()

    @objc func handleLogin() {
    print("Logging In!!!")
    }

}

我想要达到的目标

下面的代码不起作用

视图控制器

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(loginRegisterButton)


}

lazy var loginRegisterButton: UIButton = {
    let button = UIButton(type: .system)
    button.backgroundColor = Color.darkBlue
    button.setTitle("Register", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitleColor(UIColor.white, for: .normal)
    button.layer.cornerRadius = 5
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)

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

    return button
}()

}

登录函数

import Foundation
import UIKit

class LoginFunctions {

@objc func handleLogin() {
    print("Logging In!!!")
}
}

几天来我一直在尝试调试它,但没有成功。任何帮助将不胜感激。提前致谢!

您的 ViewController 没有对您的 LoginFunctions 的引用。您将 self 作为目标传递给按钮,但 self 没有 handleLogin 方法。

您需要在 ViewController class 中保留 LoginFunctions 的实例。然后将该引用作为目标而不是 self.

class ViewController: UIViewController {
    let functions = LoginFunctions()

    lazy var loginRegisterButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = Color.darkBlue
        button.setTitle("Register", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitleColor(UIColor.white, for: .normal)
        button.layer.cornerRadius = 5
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)

        button.addTarget(functions, action: #selector(LoginFunctions.handleLogin), for: .touchUpInside)

        return button
    }()
}

要将目标添加到 class 它必须包含选择器中的函数,您可以尝试在视图控制器之间共享方法

extension UIViewController 
{
    @objc func handleLogin() {
         print("Logging In!!!")
    }

}