Search code examples
iosswiftuiviewcontrolleruipangesturerecognizer

how to move the secondViewController from the top of the firstViewController using panGesture?


I'm trying to move the secondViewController off the firstViewController's top using panGesture but I'm running into a problem...

when I start moving the secondViewController a black screen show up right behind the controller and not the firstViewController (as I expected) and I don't know how to fix this problem...

here's the code that illustrate my problem...

firstVC here..

import UIKit

class mainController: UIViewController {

    let tapGestureRecognizer = UITapGestureRecognizer()
    let secondVC = SecondViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        tapGestureRecognizer.addTarget(self, action: #selector(goToSecondVC))

        view.backgroundColor = UIColor.red
        view.addGestureRecognizer(tapGestureRecognizer)
    }

    @objc func goToSecondVC(){
        present(secondVC, animated: true, completion: nil)
    }        
}

and secondVC here..

import UIKit

class SecondViewController: UIViewController {

    let panGesture = UIPanGestureRecognizer()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.green

        panGesture.addTarget(self, action: #selector(moveView))

        view.addGestureRecognizer(panGesture)
    }

    @objc func moveView(pan: UIPanGestureRecognizer){
        let translation = pan.translation(in: view)

        if pan.state == .began{
            print("began")

        } else if pan.state == .changed {

            view.frame.origin.x += translation.x

            pan.setTranslation(CGPoint.zero, in: view)
        } else if pan.state == .ended{

            print("ended")                
        }
    }
}

why there's a black screen behind the second view controller after present secondViewController?


Solution

  • You just need to set your SecondViewController's modalPresentationStyle correctly…

    @objc func goToSecondVC(){
        secondVC.modalPresentationStyle = .overCurrentContext
        present(secondVC, animated: true, completion: nil)
    }