ScrollView无法识别摇动手势
我有3个档案。
1.ContentVC-包含在视图控制器之间滑动的scrollView
2.FirstVC-包含摇动手势功能
3.SecondVC-默认视图控制器
当我摇晃设备时,什么也没有发生。
ContentVC.swift
class ContainerVC: UIViewController {
@IBOutlet weak var scroll: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let left = self.storyboard?.instantiateViewController(withIdentifier: "vw") as! UINavigationController
self.addChild(left)
self.scroll.addSubview(left.view)
self.didMove(toParent: self)
let last = self.storyboard?.instantiateViewController(withIdentifier: "lastviewNav") as! UINavigationController
self.addChild(last)
self.scroll.addSubview(last.view)
self.didMove(toParent: self)
var middleframe:CGRect = last.view.frame
middleframe.origin.x = self.view.frame.width
last.view.frame = middleframe
self.scroll.contentSize = CGSize(width: (self.view.frame.width) * 2, height: (self.view.frame.height))
}
}
FirstVC.swift
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if event?.subtype == UIEvent.EventSubtype.motionShake {
if motion == .motionShake {
print("quote is appearing by shaking the device")
} else {
print("No quote is coming")
}
}
}
最佳答案
运动事件最初传递给第一响应者,并在适当时沿响应者链转发。
https://developer.apple.com/documentation/uikit/uiresponder/1621090-motionended
因此,请确保:
FirstVC
能够成为第一响应者:override var canBecomeFirstResponder: Bool {
return true
}
FirstVC
是特定时间点的第一响应者:firstVC.becomeFirstResponder()
现在,您的
UIViewController
将能够接收震动事件。您可以阅读有关响应者链的更多信息:How do Responder Chain Works in IPhone? What are the "next responders"?