Prateek Varshney
Prateek Varshney

Reputation: 1421

Scrolling scrollview based on pan gesture translation

I want to know how to convert pan gesture y translation to equivalent of a scrollview content y offset.

So in this I can scroll my scrollview through pan gesture translation reproducing the same effect of a natural scrollview scrolling.

let scrollYOffset: CGFloat = panGesture.translation(in: view).y

When I did this it resulted in a very jerky scrolling as the scrollYOffset value changed from 0 to 54 and then 124 on dragging.

What I want is a smooth and natural scrolling of a scrollview using pan gesture.

You may ask why I am not using the natural scrollview and its delegate -

func scrollViewDidScroll(_ scrollView: UIScrollView)

and the answer is I am trying to build an app where a user can drag an object on the screen and the scrollview behind it should scroll by that much.

Can anyone help me in converting the pan gesture y translation into scrollview y content offset.

Any help will be appreciated. Thanks.

Upvotes: 1

Views: 1930

Answers (2)

DonMag
DonMag

Reputation: 77690

There are various methods to get a "smooth draggable view" --- but, for your purpose, a possible option would be to use a UISlider:

enter image description here

If desired, you can change the appearance of the slider by setting the thumb and track images.

Example code (used for that screen-cap):

class SliderScrollViewController: UIViewController, UIScrollViewDelegate {
    
    let scrollView: UIScrollView = UIScrollView()
    let slider: UISlider = UISlider()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        [scrollView, slider].forEach {
            view.addSubview($0)
            $0.translatesAutoresizingMaskIntoConstraints = false
        }

        // horizontal stack view to hold scroll content
        let stack = UIStackView()
        stack.distribution = .fillEqually
        stack.spacing = 8
        stack.translatesAutoresizingMaskIntoConstraints = false

        // add 20 views to the stack view for horizontal scrolling
        for i in 1...20 {
            let v = UILabel()
            v.textAlignment = .center
            v.backgroundColor = .yellow
            v.text = "View \(i)"
            stack.addArrangedSubview(v)
        }
        stack.arrangedSubviews.first?.widthAnchor.constraint(equalToConstant: 120).isActive = true
        scrollView.addSubview(stack)
        
        let g = view.safeAreaLayoutGuide
        let svCLG = scrollView.contentLayoutGuide
        let svFLG = scrollView.frameLayoutGuide
        
        NSLayoutConstraint.activate([

            scrollView.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            scrollView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            scrollView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            scrollView.heightAnchor.constraint(equalToConstant: 120.0),
            
            slider.topAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 20.0),
            slider.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            slider.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            
            stack.topAnchor.constraint(equalTo: svCLG.topAnchor, constant: 8.0),
            stack.leadingAnchor.constraint(equalTo: svCLG.leadingAnchor, constant: 8.0),
            stack.trailingAnchor.constraint(equalTo: svCLG.trailingAnchor, constant: -8.0),
            stack.bottomAnchor.constraint(equalTo: svCLG.bottomAnchor, constant: 8.0),

            stack.heightAnchor.constraint(equalTo: svFLG.heightAnchor, constant: -16.0),
            
        ])
        
        slider.addTarget(self, action: #selector(self.sliderChanged(_:)), for: .valueChanged)
        
        // so we can see the frame of the scroll view
        scrollView.backgroundColor = .green
        
        // set scrollView delegate
        scrollView.delegate = self
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // we need to update the slider position when scroll view is manually scrolled
        let w = scrollView.contentSize.width - scrollView.frame.size.width
        let pct = scrollView.contentOffset.x / w
        slider.value = Float(pct)
    }

    @objc func sliderChanged(_ sender: UISlider) -> Void {
        // set scroll view's content offset x based on position of slider
        let w = scrollView.contentSize.width - scrollView.frame.size.width
        let x = w * CGFloat(sender.value)
        scrollView.contentOffset.x = x
    }
    
}

Edit

Thought I'd play around with this a bit more... this example grabs the scroll view's content as a UIImage, uses that for a "background" image behind the slider, and creates an outlined image for the slider's thumb:

enter image description here

enter image description here

Complete code:

class SliderScrollViewController: UIViewController, UIScrollViewDelegate {
    
    let scrollView: UIScrollView = UIScrollView()
    let scrollContentView: UIView = UIView()
    let slider: UISlider = UISlider()
    let sliderBKG: UIImageView = UIImageView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        [scrollView, sliderBKG, slider].forEach {
            view.addSubview($0)
            $0.translatesAutoresizingMaskIntoConstraints = false
        }
        
        // horizontal stack view to hold scroll content
        let stack = UIStackView()
        stack.distribution = .fillEqually
        stack.spacing = 8
        stack.translatesAutoresizingMaskIntoConstraints = false
        
        // add 20 views to the stack view for horizontal scrolling
        for i in 1...20 {
            let v = UILabel()
            v.textAlignment = .center
            v.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 1.0 - (CGFloat(i) * 0.05), alpha: 1.0)
            v.text = "View \(i)"
            stack.addArrangedSubview(v)
        }
        stack.arrangedSubviews.first?.widthAnchor.constraint(equalToConstant: 120).isActive = true
        
        scrollContentView.translatesAutoresizingMaskIntoConstraints = false
        scrollContentView.addSubview(stack)
        scrollView.addSubview(scrollContentView)
        
        let g = view.safeAreaLayoutGuide
        let svCLG = scrollView.contentLayoutGuide
        let svFLG = scrollView.frameLayoutGuide
        
        NSLayoutConstraint.activate([
            
            scrollView.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            scrollView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            scrollView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            scrollView.heightAnchor.constraint(equalToConstant: 120.0),
            
            slider.topAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 20.0),
            slider.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            slider.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            slider.heightAnchor.constraint(equalToConstant: 40.0),
            
            sliderBKG.topAnchor.constraint(equalTo: slider.topAnchor, constant: 6.0),
            sliderBKG.leadingAnchor.constraint(equalTo: slider.leadingAnchor, constant: 0.0),
            sliderBKG.trailingAnchor.constraint(equalTo: slider.trailingAnchor, constant: 0.0),
            sliderBKG.bottomAnchor.constraint(equalTo: slider.bottomAnchor, constant: -6.0),
            
            scrollContentView.topAnchor.constraint(equalTo: svCLG.topAnchor, constant: 0.0),
            scrollContentView.leadingAnchor.constraint(equalTo: svCLG.leadingAnchor, constant: 0.0),
            scrollContentView.trailingAnchor.constraint(equalTo: svCLG.trailingAnchor, constant: 0.0),
            scrollContentView.bottomAnchor.constraint(equalTo: svCLG.bottomAnchor, constant: 0.0),
            
            scrollContentView.heightAnchor.constraint(equalTo: svFLG.heightAnchor, constant: 0.0),
            
            stack.topAnchor.constraint(equalTo: scrollContentView.topAnchor, constant: 8.0),
            stack.leadingAnchor.constraint(equalTo: scrollContentView.leadingAnchor, constant: 8.0),
            stack.trailingAnchor.constraint(equalTo: scrollContentView.trailingAnchor, constant: -8.0),
            stack.bottomAnchor.constraint(equalTo: scrollContentView.bottomAnchor, constant: -8.0),
            
        ])
        
        slider.addTarget(self, action: #selector(self.sliderChanged(_:)), for: .valueChanged)
        
        // set slider images to clear images
        slider.setThumbImage(UIImage(), for: [])
        slider.setMinimumTrackImage(UIImage(), for: [])
        slider.setMaximumTrackImage(UIImage(), for: [])
        
        // so we can see the frame of the scroll view
        scrollView.backgroundColor = .green
        scrollContentView.backgroundColor = .orange
        
        // set scrollView delegate
        scrollView.delegate = self
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // after view has appeared (so we know auto-layout has finished)
        // grab the content of the scroll view as a UIImage
        let img = scvSnapshot()
        // set it to the "background" image view behind the slider
        sliderBKG.image = img
        updateThumbImage()
    }
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: { _ in
        }, completion: {
            _ in
            self.updateThumbImage()
        })
    }
    func updateThumbImage() -> Void {
        // generate a proportional width bordered clear image
        let w = self.scrollView.frame.width * (self.scrollView.frame.width / self.scrollView.contentSize.width)
        let rect = CGRect(origin: .zero, size: CGSize(width: w, height: 40.0))
        let renderer = UIGraphicsImageRenderer(size: rect.size)
        let img = renderer.image { rc in
            rc.cgContext.setFillColor(UIColor.clear.cgColor)
            rc.cgContext.setStrokeColor(UIColor.red.cgColor)
            rc.cgContext.setLineWidth(2)
            rc.cgContext.addRect(rect)
            rc.cgContext.drawPath(using: .fillStroke)
        }
        // set the slider's custom thumb image
        self.slider.setThumbImage(img, for: [])
    }
    func scvSnapshot() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: scrollContentView.bounds)
        return renderer.image { rendererContext in
            scrollContentView.layer.render(in: rendererContext.cgContext)
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // we need to update the slider position when scroll view is manually scrolled
        let w = scrollView.contentSize.width - scrollView.frame.size.width
        let pct = scrollView.contentOffset.x / w
        slider.value = Float(pct)
    }
    
    @objc func sliderChanged(_ sender: UISlider) -> Void {
        // set scroll view's content offset x based on position of slider
        let w = scrollView.contentSize.width - scrollView.frame.size.width
        let x = w * CGFloat(sender.value)
        scrollView.contentOffset.x = x
    }
    
}

Upvotes: 0

Vitalii Shvetsov
Vitalii Shvetsov

Reputation: 422

Method translation: returns a difference between a previous and current iterations, so you should add the translation to the existing result, something like this.

     @objc private func handleGesture(panGestureRecognizer: UIPanGestureRecognizer) {
         switch panGestureRecognizer.state {
         case .begin:
            break
         case .changed:
            let translation = panGestureRecognizer.translation(in: self.view)
            panGestureRecognizer.setTranslation(.zero, in: self.view)

            let newYOffset = currentOffset + translation.y
         case .ended:
            break
         }
     }

Upvotes: 2

Related Questions