我只需要在我的一个应用程序中实现这一点。
我通过添加一个覆盖整个视图的按钮来使其工作,一旦点击此按钮就会触发 VC 被关闭。
添加按钮后,您可以在顶部添加自定义视图。
到目前为止,它看起来运行良好。
下面是我的代码(我以编程方式完成所有操作,没有情节提要)
//—————————————————————————————
// MARK: View Life Cycle
//—————————————————————————————
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clear //VC view background transparent
setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//Animate blackView opacity to 1 to give some depth
UIView.animate(withDuration: 0.4, delay: 0.2, options: .curveEaseInOut, animations: {
self.blackView.alpha = 1
})
}
//————————————————
// MARK: Setup UI
//————————————————
let blackView: UIView = {
let view = UIView()
view.alpha = 0.0
view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
return view
}()
//Invisible button which covers the entire view that can be tapped
lazy var dismissLayerBtn: UIButton = {
let btn = UIButton()
btn.addTarget(self, action: #selector(tapToDismiss), for: .touchUpInside)
return btn
}()
@objc func tapToDismiss() {
print("tapToDimiss")
self.dismiss(animated: true, completion: nil)
}
let milestonePickerView: MilestonePickerView = {
let view = MilestonePickerView(frame: .zero)
return view
}()
func setupUI() {
view.addSubview(blackView)
view.addSubview(dismissLayerBtn)
view.addSubview(milestonePickerView) //Important to add the customView after the button.
blackView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
dismissLayerBtn.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
milestonePickerView.anchor(top: nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 20, paddingBottom: 40, paddingRight: 20, width: 0, height: 400)
//I'm using a custom extension to setup constraints (anchors)
}
如果您使用故事板,请确保将不可见按钮放在自定义视图下。
我希望这有帮助。