RealityKit中ARView多点触摸失效问题求解决方案
问题:ARView中无法检测双指触摸操作,touches.count始终为1
我需要通过touchesMoved函数检测双指操作,代码会打印触摸点数量。该程序在普通UIView中可正常运行(打印touches.count=2),但在ARView中始终显示touches.count=1,请问有什么解决办法?
用户提供的测试代码:
import UIKit import RealityKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.isMultipleTouchEnabled = true // // 这段代码可正常检测双指 // let v = UIView(frame: view.frame) // v.backgroundColor = .green // view.addSubview(v) // v.isMultipleTouchEnabled = true // 这段代码无法检测双指 let arView = ARView(frame: view.frame, cameraMode: .nonAR, automaticallyConfigureSession: true) view.addSubview(arView) arView.isMultipleTouchEnabled = true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print("touchesBegan, touches.count=\(touches.count)") } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { print("touchesMoved, touches.count=\(touches.count)") } }
解决办法
1. 自定义ARView子类重写触摸方法
ARView的内部视图层级会拦截触摸事件,导致ViewController无法接收到完整的触摸集合。直接在ARView子类中重写触摸方法,能确保捕获到所有触摸点:
import UIKit import RealityKit class CustomARView: ARView { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) print("touchesBegan, touches.count=\(touches.count)") } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) print("touchesMoved, touches.count=\(touches.count)") } }
然后在ViewController中替换为自定义子类:
class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.isMultipleTouchEnabled = true let arView = CustomARView(frame: view.frame, cameraMode: .nonAR, automaticallyConfigureSession: true) view.addSubview(arView) arView.isMultipleTouchEnabled = true } }
2. 禁用ARView默认手势(可选)
ARView默认自带捏合、旋转等手势识别器,这些手势会抢占触摸事件。如果不需要默认手势,可以禁用它们:
// 创建ARView后添加以下代码 arView.enableTranslateGestures = false arView.enableRotateGestures = false arView.enableScaleGestures = false
3. 确保所有子视图启用多触摸
递归设置ARView及其所有子视图的isMultipleTouchEnabled和isUserInteractionEnabled为true,避免子视图拦截触摸事件:
// 定义递归函数 func enableFullMultipleTouch(for view: UIView) { view.isMultipleTouchEnabled = true view.isUserInteractionEnabled = true view.subviews.forEach { enableFullMultipleTouch(for: $0) } } // 在添加ARView后调用 enableFullMultipleTouch(for: arView)
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

