首页 > 解决方案 > 在 UILabel 上点击崩溃 - 使用 UIApplication 共享 keyWindow rootViewController

问题描述

我对 Swift 很陌生,我正在为混合应用程序(Cordova)编写一个插件。

我设法让 App rootController 显示一个 ViewController ,里面有一个游戏,顶部有一个单独的 UIView 标题,其中包含一个 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 On-Demand Resources 启动一个 html5 游戏。

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

标签: iosswiftobjective-cxcodehybrid-mobile-app

解决方案


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

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

也总是喜欢#selectorSelector因为如果你使用错误的选择器,它会给你一个错误。


推荐阅读