将 Traget 添加到 UIView 中的 UIButton。收到错误 "terminating with uncaught exception of type NSException"

addTraget to UIButton in UIView. getting error "terminating with uncaught exception of type NSException"

我有一个 UIView class,在里面我有一个 UIButton,点击它应该会打开一个 UIViewController class。但是,每次我单击它时,我都会在 AppDelegate - Thread 1: signal SIGABRT 中收到错误消息。终端:以 NSException 类型的未捕获异常终止。

lazy var signupButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Sign me up", for: .normal)
    button.setTitleColor(UIColor.blue, for: .normal)
    button.backgroundColor = UIColor.white
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.addTarget(self, action: #selector(handleLogin(vc:)), for: .touchUpInside)
    return button
}()

@objc func handleLogin(vc: UIViewController) {
    let loginController = LoginController()
    vc.present(loginController, animated: true, completion: nil)
}

问题出在 func handleLogin 的参数上。您已将其设置为期望 UIViewController 的实例,但它实际上是选择器的发送者,在本例中为 UIButton

您需要更新为:

@objc func handleLogin(sender: UIButton) {
   let loginController = LoginController()
   present(loginController, animated: true, completion: nil)
}

您可以交替执行此操作,因为您根本不需要 sender 参数。

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

@objc func handleLogin() {
   let loginController = LoginController()
   present(loginController, animated: true, completion: nil)
}