微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

currentContext 表示样式更改子视图控制器视图的大小

如何解决currentContext 表示样式更改子视图控制器视图的大小

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

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: .touchUpInside)
        button.sizetoFit()
        view.addSubview(button)
    }
    
    @objc func pressed() {
        self.dismiss(animated: true,completion: nil)
    }
}

enter image description here

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

enter image description here

但是,当我关闭它时,ChildVC 的主视图的大小占据了整个屏幕:

enter image description here

当我记录 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)
    }

这将防止不必要的升级。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。