我在应用程序的主屏幕上添加了一个按钮,点按一个按钮,就会出现一个新的viewcontroller
。这在模拟器中完全正常,但是当我在实际的iPhone中尝试时,它会导致应用程序崩溃。
此外,崩溃仅在登录按钮上引起,而注册按钮以相同的方式完成
我将保留下面的代码
var loginButton = UIButton()
var signUpButton = UIButton()
loginButton.setTitle("Login", for: .normal)
loginButton.titleLabel?.textAlignment = .center
loginButton.backgroundColor = appGreenTheme
loginButton.titleLabel?.textColor = .white
loginButton.layer.cornerRadius = 20
loginButton.titleLabel?.font = UIFont.systemFont(ofSize: 20)
loginButton.setBackgroundImage(UIImage(named: "pinkOrangeGradientPDF"), for: .normal)
loginButton.clipsToBounds = true
signUpButton.setTitle("Sign Up", for: .normal)
signUpButton.setTitleColor(.black, for: .normal)
signUpButton.titleLabel?.textAlignment = .center
signUpButton.backgroundColor = .white
signUpButton.titleLabel?.textColor = .black
signUpButton.layer.cornerRadius = 20
signUpButton.titleLabel?.font = UIFont.systemFont(ofSize: 20)
loginButton.addTarget(self, action: #selector(loginButtonTapped1(_:)), for: .allTouchEvents)
signUpButton.addTarget(self, action: #selector(signUpButtonTapped1(_:)), for: .allTouchEvents)
///////////////////////////////////////////////////
@objc func loginButtonTapped1(_ sender: UIButton) {
let nav = UINavigationController(rootViewController: LoginViewController())
self.present(nav, animated: true, completion: nil)
}
@objc func signUpButtonTapped1(_ sender: UIButton) {
let nav = UINavigationController(rootViewController: SignUpViewController())
self.present(nav, animated: true, completion: nil)
}
我也试过“touchUpInside”事件。再次,它在模拟器中完美运行,但在物理设备中却无法运行。
欢迎任何帮助。
以下是日志中显示的错误
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SparkGPS.LoginView addTarget:action:forControlEvents:]: unrecognized selector sent to instance 0x13dd4c740'
答案在错误消息中。在某个地方,我的猜测是在LoginViewController
,有一个类型LoginView
的视图。这种观点称为addTarget(_:action:for:)
。 LoginView
不是UIControl
的子类,也没有addTarget(_:action:for:)
。它导致了崩溃。
让我打破-[SparkGPS.LoginView addTarget:action:forControlEvents:]
的部分。
-
意味着它是一个实例方法而不是静态或类方法。SparkGPS.LoginView
是模块和类。模块是框架或应用程序的另一个词。在这种情况下,看起来你有一个名为SparkGPS
的应用程序和一个名为LoginView
的类。addTarget:action:forControlEvents:
是addTarget(_:action:for:)
的Objective-C名称。最后,“选择器发送到实例”意味着变量调用方法。选择器是一种识别方法的方法,实例存储在变量中。例如,在您的代码中,您有loginButton.setTitle("Login", for: .normal)
。这可以措辞,因为setTitle(_:for:)
被发送到loginButton
实例。
您可以为按钮本身添加点按手势识别器。最好使用outlet,但这样可以正常使用,也可用于其他UI组件,如视图或标签
let loginTapGesture = UITapGestureRecognizer(target: self,
action: #selector(loginButtonTapped1))
loginButton.addGestureRecognizer(loginTapGesture)