我有一个 UIView
var transparentBackground = UIView()
单击按钮时, View 会获得一些属性
@IBAction func UserViewImage(_ sender: UIButton) -> Void {
self.transparentBackground = UIView(frame: UIScreen.main.bounds)
self.transparentBackground.backgroundColor = UIColor(white: 0.0, alpha: 0.4)
UIApplication.shared.keyWindow!.addSubview(self.transparentBackground)
self.opaqueView = self.setupOpaqueView()
self.transparentBackground.addSubview(opaqueView)
UIApplication.shared.keyWindow!.bringSubview(toFront: self.transparentBackground)
self.view.bringSubview(toFront: transparentBackground)
}
当单击另一个按钮时, View 将完全消失,并使用名为 removeAnimate 的函数。
func handleOKButtonTapped(_ sender: UIButton){
removeAnimate()
}
但是,我希望在单击背景( View )时 View 完全消失,就像单击按钮时一样,所以我这样做了:
override func viewDidLoad() {
super.viewDidLoad()
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(removeAnimate))
self.transparentBackground.addGestureRecognizer(gestureRecognizer)
}
但它不起作用,我不确定我做错了什么。不是透明背景 View 中有 subview 。
self.transparentBackground.addSubview(opaqueView)
最佳答案
我是这样实现的:
viewDidLoad() {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(close))
gestureRecognizer.cancelsTouchesInView = false
gestureRecognizer.delegate = self
view.addGestureRecognizer(gestureRecognizer)
}
func close() {
dismiss(animated: true, completion: nil)
}
关于ios - 基于背景点击关闭 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44834991/