currentContext presentation style 改变子视图控制器视图的大小

currentContext presentation style changes the size of the child view controller's 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)
    }
}

当我使用 currentContext 样式呈现视图控制器时,它会按原样呈现新的视图控制器,仅覆盖子视图控制器的视图:

然而,当我关闭它时,ChildVC 的主视图占据了整个屏幕:

当我记录 ChildVC 主视图的父视图时,它仍然是父视图控制器主视图的子视图,所以我不确定为什么会这样。

只需将 presentationStyle 更改为 .overCurrentContext,如下所示:

    @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)
    }

它将防止不必要的放大。