问题描述
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)
}
}
当我使用 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)
}
这将防止不必要的升级。