Louis Liang
Louis Liang

Reputation: 107

Disable scroll of a subview in a UIScrollView

I have a video player view on the top of the scroll view, and I added swipe vertically to adjust volume and brightness feature.

The problem is when I swipe in the player view to adjust the volume, the scroll view scrolls as well, how can I prevent it?

Upvotes: 2

Views: 1111

Answers (1)

Shawn Frank
Shawn Frank

Reputation: 5213

This could probably work for your use case.

I am assuming you added a pan gesture on your video view and so in your action handler, you could disable the scrollview from scrolling when the gesture's state is .began or .changed and re-enable it for any any state such as ended or cancelled

Here is how I did that:

@objc
func didPan(_ panGesture: UIGestureRecognizer)
{
    scrollView.isScrollEnabled
        = panGesture.state != .began && panGesture.state != .changed
    
    /* The above is the same as these lines of code
    if panGesture.state == .began || panGesture.state == .ended
    {
        scrollView.isScrollEnabled = false
        return
    }
    
    scrollView.isScrollEnabled = true
    */
}

Here is an example of what happens with this code:

  1. When I pan on the video, it shows a label and stops the scroll view from moving
  2. When I pan on another view inside the scrollview but outside the video region (in the yellow region), it is active

AVPlayer in UIScrollView pan gesture on UIView ioS Swift

Upvotes: 1

Related Questions