我想在用户点击除该视图之外的其他内容时从屏幕中删除UIVIew
。 (为你想象它我会上传我的观点草图)[
] 1
我想在用户点击此视图中的按钮以外的内容时删除蓝色UIview
。我该怎么用?
编辑:
蓝色UIVIew
是两个按钮,我想在用户点击背景图片时删除该视图
我做了“yerpy”告诉我要做的事,但它没有用。
func test(gestureRecognizer: UITapGestureRecognizer) {
print("test")
}
func setUpBackgroundImageView() {
self.view.addSubview(backgroundImageView)
backgroundImageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
backgroundImageView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
backgroundImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
backgroundImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
let tap = UITapGestureRecognizer(target: self, action: #selector(test(gestureRecognizer:)))
backgroundImageView.addGestureRecognizer(tap)
tap.delegate = self
}
我还将shouldReceiveTouch
函数添加到UIGestureRecognizerDelegate
。我做错了什么?
答案 0 :(得分:6)
将UIGestureRecognizer
添加到super view
:
正如您所说,您将图像视图作为背景。
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped(gestureRecognizer:)))
imageView.addGestureRecognizer(tapRecognizer)
tapRecognizer.delegate = self
添加目标操作:
func tapped(gestureRecognizer: UITapGestureRecognizer) {
// Remove the blue view.
}
然后在UITapGestureRecognizerDelegate
内:
extension ViewController : UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view!.superview!.superclass! .isSubclass(of: UIButton.self) {
return false
}
return true
}
}
希望它有所帮助!
修改强>
确保用户可以通过启用view
self.view.userInteractionEnabled = true
答案 1 :(得分:0)
您可以将UITapGestureRecognizer用于该视图
override func viewDidLoad() {
super.viewDidLoad()
// Add "tap" press gesture recognizer
let tap = UITapGestureRecognizer(target: self, action: #selector(tapHandler))
tap.numberOfTapsRequired = 1
backgroundimage.addGestureRecognizer(tap)
}
// called by gesture recognizer
func tapHandler(gesture: UITapGestureRecognizer) {
// handle touch down and touch up events separately
if gesture.state == .began {
} else if gesture.state == .ended {
}
}
答案 2 :(得分:0)
你可以
-beganTouches:(there is another para but I forget what it is)
答案 3 :(得分:0)
1-在视图下方添加视图,将其称为叠加(灰色)
2-添加所有按钮的容器视图(绿色)
3-向叠加层添加点按手势(拖动点按以覆盖视图)
4-创建tap对视图控制器的@IBAction
5-编写代码以隐藏@IBAction中的绿色视图
答案 4 :(得分:0)
在所有按钮下添加一个覆盖整个屏幕的巨型按钮。每当用户按下较小按钮下方的巨型按钮时,就可以按照自己的意愿进行操作。
不是最优雅,但可以使用:P