UIScrollView 无法识别 ShakeGesture

UIScrollView not recognising ShakeGesture

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")
        }
    }
}

Motion events are delivered initially to the first responder and are forwarded up the responder chain as appropriate.
https://developer.apple.com/documentation/uikit/uiresponder/1621090-motionended

因此请确保:

  1. FirstVC 能够成为第一响应者:
override var canBecomeFirstResponder: Bool {
    return true
}
  1. FirstVC 是特定时间点的第一响应者:
firstVC.becomeFirstResponder()

现在您的 UIViewController 将能够接收摇动事件。

您可以阅读有关响应链的更多信息:How do Responder Chain Works in IPhone? What are the "next responders"?