簡體   English   中英

斯威夫特| UIButton 導致點擊崩潰

[英]Swift | UIButton causes crash on tap

我在應用程序的主屏幕上添加了一個按鈕,點擊一個按鈕,就會出現一個新的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:是 Objective-C 的addTarget(_:action:for:)

最后,“選擇器發送到實例”意味着變量調用一個方法。 Selector是一種標識方法的方式,一個實例存儲在一個變量中。 例如,在您的代碼中有loginButton.setTitle("Login", for: .normal) 這可以表述為setTitle(_:for:)被發送到實例loginButton

您可以向按鈕本身添加點擊手勢識別器。 最好的做法是使用 outlet,但這很好用,並且對其他 UI 組件(如視圖或標簽)也很有用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM