在Swift 4中的ViewController上使用Swipe Gesture播放声音

时间:2018-01-31 16:41:41

标签: swift audio gesture

我需要知道,当一个Swipe Gesture被激活时,我如何向一个viewController添加一个wav声音(页面翻转)。我有5个不同的View Contrllers,当孩子滑动手势时,我希望它可以播放文件声音(页面翻转)。我已经在所有viewControllers(LEFT& RIGHT)上实现了Swipe Gestures,但需要声音与Gesture一起使用。

1 个答案:

答案 0 :(得分:1)

我该怎么做。在代码中将手势识别器添加到视图中,并设置一个操作,以便在每次滑动时调用。如果您需要不同的声音或行为,请获取功能中的方向。

override func viewDidLoad() {
    super.viewDidLoad()

    var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
    swipeRight.direction = UISwipeGestureRecognizerDirection.Right
    self.view.addGestureRecognizer(swipeRight)

    var swipeLeft = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
    swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
    self.view.addGestureRecognizer(swipeLeft)
}

func respondToSwipeGesture(gesture: UIGestureRecognizer) {

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {
        switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.Right:

            // Play sound here

            case UISwipeGestureRecognizerDirection.Left:

            // Play sound here

            default:
                break
        }
    }
}