ios - 在 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 游戏。
一切正常,除了返回主页按钮......
解决方案
Target
是action
应该发送到的对象。您需要移动handleTap
到您的FwViewController
或用 替换目标self
,如下所示:
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
也总是喜欢#selector
,Selector
因为如果你使用错误的选择器,它会给你一个错误。
推荐阅读
- angular - 通过 Angular swagger UI 中的代码添加授权密钥
- css - 自定义 mat-checkbox
- c# - 在方法期间的任何时候返回主菜单
- spring - 为什么 Spring Boot 应用程序不适用于 HTTP 的相对质量因子?
- java - 如何模拟 URLconnection 以便我可以更改 java 中 getLastModified 方法的返回值?
- lambda - 如果 URL 包含某些查询参数,我如何在 Lambda@Edge 查看器请求事件中强制源请求
- c# - ASP.NET core 3 ActionFilter 和 Viewbag
- python - 是否可以从 Python 中的另一个子类调用方法?
- ios - UIDatePicker iOS 14 简洁风格移除默认背景
- machine-learning - 变分自动编码器:MSE 与 BCE