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")
}
}
}
答案 0 :(得分:2)
运动事件最初传递给第一响应者,并在适当时沿响应者链转发。
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"?