首页 > 解决方案 > 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?

标签: iosswiftuiviewcontrolleruipangesturerecognizer

解决方案


您只需要正确设置您SecondViewController的 ' modalPresentationStyle...</p>

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

推荐阅读