斯威夫特| UIButton导致点击崩溃

时间:2019-04-25 07:21:49

标签: ios swift uinavigationcontroller uibutton presentviewcontroller

我在应用程序的主屏幕上添加了一个按钮,点击按钮后,会显示一个新的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'

2 个答案:

答案 0 :(得分:1)

答案在错误消息中。我的猜测是在某个地方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

答案 1 :(得分:0)

您可以向按钮本身添加点击手势识别器。最好的方法是使用插座,但这很好用,并且对其他UI组件(例如视图或标签)也很有用

let loginTapGesture = UITapGestureRecognizer(target: self,
                                                 action: #selector(loginButtonTapped1))
loginButton.addGestureRecognizer(loginTapGesture)