【问题标题】:currentContext presentation style changes the size of the child view controller's viewcurrentContext 表示样式改变子视图控制器视图的大小
【发布时间】:2021-04-07 05:15:43
【问题描述】:

我有一个父视图控制器和一个子视图控制器,它们占据了父视图的一部分:

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 的主视图的超级视图时,它仍然是父视图控制器主视图的子视图,所以我不确定为什么会这样。

【问题讨论】:

    标签: ios swift uiviewcontroller uimodalpresentationstyle


    【解决方案1】:

    只需将您的 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)
        }
    

    它将防止不必要的升级。

    【讨论】:

    • 谢谢,它有效。但是,现在modalTransitionStyle 没有得到足够的尊重。
    • @Kevvv 检查我的编辑版本,我相信它可以解决问题。
    猜你喜欢
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 2019-07-11
    • 2014-06-11
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多