如何实现半透明的uiviewcontroller

目标:通过self.present弹出新窗口,达到半透明的效果;类似uiviewcontroller

错误的位置:

1
2
3
4
5
override func viewDidLoad() {
super.viewDidLoad()
self.modalPresentationStyle = .overCurrentContext
view.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}

正确的位置:

1
2
3
4
5
6
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

self.modalPresentationStyle = .overCurrentContext
view.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}

原因:
当新窗口弹出的动画结束后,底层的view其实已经不存在了,所以半透明就看不见他了:
After your modal view animates in, it is resized to be equal in size to its parent view. What you can do is inside your viewDidAppear:, take a picture of the parentController’s view, then insert a UIImageView containing the picture of the parent at the back of your own view’s list of subviews:

但如果在init中设置了alpha值,系统貌似帮我们做了这些事。

Contents
,