Swift开发:如何实现等待屏幕点击后执行视图淡出移除?
实现点击屏幕触发视图淡出并移除的方案
嘿,我来帮你搞定这个点击触发淡出的需求~ 下面给你两种常用的实现方式,还会顺便修正你原代码里的小拼写错误哦!
方法一:添加UITapGestureRecognizer(灵活可控)
这种方式可以精准控制点击区域,不管是全屏点击还是指定区域都能实现。
首先,先修正你原代码里的拼写问题,再添加点击手势:
// 修正拼写错误:lebel → label,muView → myView let myView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100)) myView.backgroundColor = .lightGray // 加个背景色方便查看 let label = UILabel(frame: CGRect(x:0,y:0,width: 100, height: 100)) label.text = "点击屏幕关闭" label.textAlignment = .center myView.addSubview(label) self.view.addSubview(myView) myView.alpha = 0 UIView.animate(withDuration: 0.5, animations: { myView.alpha = 1 }) // 给当前控制器的view添加全屏点击手势 let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleScreenTap)) // 如果不想让点击myView本身触发,可以设置cancelsTouchesInView = false // tapGesture.cancelsTouchesInView = false self.view.addGestureRecognizer(tapGesture)
然后在你的视图控制器里实现点击后的处理方法:
// 注意:如果myView是局部变量,需要把它改成控制器的属性,不然这里访问不到 private var myView: UIView? @objc private func handleScreenTap() { guard let targetView = myView else { return } UIView.animate(withDuration: 0.5, animations: { targetView.alpha = 0 }, completion: { _ in targetView.removeFromSuperview() self.myView = nil // 释放引用 // 移除手势,避免后续重复触发 if let tap = self.view.gestureRecognizers?.first(where: { $0 is UITapGestureRecognizer }) { self.view.removeGestureRecognizer(tap) } }) }
方法二:重写视图控制器的touchesBegan方法
如果你的场景不需要复杂的手势逻辑,直接重写控制器的触摸方法更简洁:
第一步,先把myView定义为控制器的属性:
class YourViewController: UIViewController { private var myView: UIView? // 定义为可选属性,方便后续判断 // ... 其他控制器代码 ... }
然后在创建视图的地方赋值并执行渐显动画:
myView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100)) myView?.backgroundColor = .lightGray let label = UILabel(frame: CGRect(x:0,y:0,width: 100, height: 100)) label.text = "点击屏幕关闭" label.textAlignment = .center myView?.addSubview(label) self.view.addSubview(myView!) myView?.alpha = 0 UIView.animate(withDuration: 0.5, animations: { self.myView?.alpha = 1 })
最后重写touchesBegan方法处理点击事件:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) guard let targetView = myView else { return } UIView.animate(withDuration: 0.5, animations: { targetView.alpha = 0 }, completion: { _ in targetView.removeFromSuperview() self.myView = nil // 释放引用 }) }
额外提醒
你原代码里有两个拼写错误,会导致编译失败,一定要修改:
lebel→labelmuView→myView
内容的提问来源于stack exchange,提问作者Jeronimo Cabezuelo Ruiz
相关产品推荐
相关产品推荐

