Swift中使用Lottie动画添加子视图后按钮无法点击如何解决
问题根因
你的全屏AnimationView默认会接收用户交互事件,添加到视图后层级位于按钮之上,动画播放完成后仍常驻在视图层级最上方,后续所有按钮点击事件都会被该动画视图拦截,导致按钮无响应。另外你在懒加载方法中重复调用了两次view.addSubview(animationView),属于冗余代码可以删除。
解决方案
调整动画视图的交互配置和生命周期逻辑,动画播放完成后自动隐藏/移除,避免拦截按钮点击:
- 初始化动画视图时默认关闭用户交互、设置为隐藏状态,避免初始状态就遮挡按钮
- 调用动画播放方法时传入完成回调,动画播放结束后立即隐藏动画视图
- 删除冗余的重复添加子视图代码
修改后的完整代码如下:
import Lottie class ViewController: UIViewController { lazy var backgroundAnimationView: AnimationView = { let animationView = AnimationView() // 关闭用户交互,不会拦截下层视图的点击事件 animationView.isUserInteractionEnabled = false // 初始状态隐藏 animationView.isHidden = true view.addSubview(animationView) animationView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ animationView.topAnchor.constraint(equalTo: view.topAnchor), animationView.rightAnchor.constraint(equalTo: view.rightAnchor), animationView.leftAnchor.constraint(equalTo: view.leftAnchor), animationView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) return animationView }() private func playBackgroundAnimation(){ let animation = Animation.named("confettiBurst") backgroundAnimationView.animation = animation // 播放前显示动画视图 backgroundAnimationView.isHidden = false // 播放动画,传入完成回调 backgroundAnimationView.play(fromProgress: 0, toProgress: 1, loopMode: .playOnce) { [weak self] _ in // 播放完成后隐藏动画视图 self?.backgroundAnimationView.isHidden = true } } @IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() button.layer.cornerRadius = 15 } @IBAction func rollButtonPress(_ sender: UIButton) { playBackgroundAnimation() print("button tapped") } }
如果不需要保留动画视图复用,也可以在播放完成后调用backgroundAnimationView.removeFromSuperview()直接移除,下次点击再重新创建即可。
内容的提问来源于stack exchange,提问作者Patryk Piwowarczyk
相关产品推荐
相关产品推荐

