崩溃点击 UILabel - 使用 UIApplication shared keyWindow rootViewController

Crash tapping on UILabel - using UIApplication shared keyWindow rootViewController

我是 Swift 的新手,我正在为混合应用程序 (Cordova) 编写插件。

我设法让 App rootController 显示一个 ViewController,里面有一个游戏,顶部有一个单独的 UIView header,其中包含一个 UILabel 作为后退按钮。

我一点击后退按钮就遇到了崩溃。 我做错了什么?

import SomeFramework;

@objc (MyIntegration) class MyIntegration : SomeFrameworkDelegate {
    func implementedFunctionForDelegate(_ controller: FwViewController) {
      print("fwViewControllerDidHandleSomeEvent");
    }
    // ...

    @objc(launchGame:)
    func launchGame() {
      // Prep params
      let params = FwLaunchParameters.init()
      params.gameId = gameId
      
      // ViewController init
      let gameController = FwViewController.init(gameLaunchParameters: params)
      gameController.delegate = self
      
      // Display game using rootViewController
      let currentWindow: UIWindow? = UIApplication.shared.keyWindow
      currentWindow?.rootViewController?.present(gameController, animated: true, completion: nil)

      let backHomeHeader = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 80.0))
      let label = UILabel(frame: CGRect(x: 0, y: 28, width: 200, height: 50))
      label.text = "\u{3008} Back Home"
      label.isUserInteractionEnabled = true
      let gestureRecognizer = UITapGestureRecognizer(target: currentWindow?.rootViewController, action: Selector("handleTap"))
      label.addGestureRecognizer(gestureRecognizer)
      
      handleTap() // prints out the log as expected

      // Display header
      currentWindow?.addSubview(backHomeHeader)
      backHomeHeader.addSubview(label)
    }

    @objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {
      print("tapped! yay!")
    }
}

崩溃前的错误日志:

2021-07-31 01:17:24.790750-0400 MyApp[53004:2197131] -[MainViewController handleTap]: unrecognized selector sent to instance 0x7fdb44906490
2021-07-31 01:17:24.842133-0400 MyApp[53004:2197131] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MainViewController handleTap]: unrecognized selector sent to instance 0x7fdb44906490'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff20422fba __exceptionPreprocess + 242
    1   libobjc.A.dylib                     0x00007fff20193ff5 objc_exception_throw + 48

注意:我使用 UIApplication.shared.keyWindow 因为它是一个混合应用程序 (Cordova),我正在编写一个插件,允许一些 Javascript 代码使用 Apple html5 启动游戏 On-Demand资源。

除了“返回主页”按钮外,一切正常...

崩溃表明 MainViewController 没有名称为 handleTap

的方法

似乎 currentWindow?.rootViewControllerMainViewControllerhandleTap 函数在 MyIntegration class.

因此,在这种情况下,将 self 作为目标传递或在 MainViewController 中实现 handleTap

Targetaction 应该发送到的对象。您需要将 handleTap 移至 FwViewController 或将目标替换为 self,如下所示:

let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))

也总是更喜欢 #selector 而不是 Selector 因为如果你使用了错误的选择器,它会给你一个错误。