iosswiftuiviewcontrolleruimodalpresentationstyle

currentContext presentation style changes the size of the child view controller's view


I have a parent view controller and a child view controller that takes up a portion of the parent's main view:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let childVC = ChildVC()
        addChild(childVC)
        childVC.view.frame = CGRect(origin: CGPoint(x: 100, y: 100), size: CGSize(width: 200, height: 200))
        view.addSubview(childVC.view)
        childVC.didMove(toParent: self)
    }
}

class ChildVC: UIViewController {
    override func loadView() {
        let v = UIView()
        v.backgroundColor = .cyan
        view = v
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton(type: .system)
        button.setTitle("Present", for: .normal)
        button.addTarget(self, action: #selector(pressed), for: .touchUpInside)
        button.sizeToFit()
        view.addSubview(button)

    }
    
    @objc func pressed() {
        self.definesPresentationContext = true
        self.providesPresentationContextTransitionStyle = true
        self.modalTransitionStyle = .crossDissolve
        let pvc = PresentedVC()
        pvc.modalPresentationStyle = .currentContext
        self.present(pvc, animated: true, completion: nil)
    }
}

class PresentedVC: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .yellow
        
        let button = UIButton(type: .system)
        button.setTitle("Dismiss", for: .normal)
        button.addTarget(self, action: #selector(pressed), for: .touchUpInside)
        button.sizeToFit()
        view.addSubview(button)
    }
    
    @objc func pressed() {
        self.dismiss(animated: true, completion: nil)
    }
}

enter image description here

When I present a view controller using the currentContext style, it presents the new view controller as it should, covering only the child view controller's view:

enter image description here

However, when I dismiss it, the size of the ChildVC's main view takes up the entire screen:

enter image description here

When I log the superview of the ChildVC's main view, it's still a subview of the parent view controller's main view so I'm not sure why this is happening.


Solution

  • Just change your presentationStyle to .overCurrentContext like this:

        @objc func pressed() {
            self.definesPresentationContext = true
            self.providesPresentationContextTransitionStyle = true
            self.modalTransitionStyle = .crossDissolve
            let pvc = PresentedVC()
            pvc.modalPresentationStyle = .overCurrentContext // <-- here
            pvc.modalTransitionStyle = .crossDissolve        // <-- and here
            self.present(pvc, animated: true, completion: nil)
        }
    

    It will prevent the unwanted upscaling.