Xcode中如何用IF语句检测特定View Controller 避免触摸响应崩溃
解决方案
直接在触摸响应方法的最开头加前置守卫判断,只有当前Game View Controller处于前台可交互状态、未被其他界面遮挡、未被移出控制器栈时,才执行后续触摸逻辑,从根源避免后台状态下触发游戏逻辑导致崩溃。
修改后的完整代码
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // 前置判断:仅当前控制器处于前台可交互状态时才响应触摸 guard viewIfLoaded?.window != nil, !isBeingDismissed, !isMovingFromParent, (navigationController == nil || navigationController?.topViewController == self), presentedViewController == nil else { return } // First touch to start the game if gameState == .ready { startGame() } if let touchLocation = event?.allTouches?.first?.location(in: self.view) { // Move the player to the new position movePlayer(to: touchLocation) // Move all enemies to the new position to trace the player moveEnemies(to: touchLocation) } }
补充优化措施
- 可通过视图生命周期联动控制交互开关,进一步规避异常触摸穿透问题:
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) view.isUserInteractionEnabled = true } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) view.isUserInteractionEnabled = false } - 如果跳转后的新控制器使用了
overFullScreen/overCurrentContext的半透明弹出样式,建议调整modalPresentationStyle为默认自动样式,从系统层级上避免下层控制器接收穿透的触摸事件。
内容的提问来源于stack exchange,提问作者Pressing_Keys_24_7
相关产品推荐
相关产品推荐

