Swift中UIImageView实现淡入动画后点击触发淡出效果的问题咨询
UIImageView运行时点击触发淡出效果实现方案
核心修改步骤
- 给UIImageView开启用户交互,添加点击手势识别器
- 原有淡入动画新增
allowUserInteraction配置,保证动画过程中可响应交互 - 点击事件中先校验动画是否处于运行状态,再执行淡出逻辑
代码实现
1. 修改原有淡入动画代码
// 新增.allowUserInteraction选项,允许动画运行时响应交互 UIView.animate(withDuration: 0.5, delay: delay, options: [.curveEaseOut, .allowUserInteraction], animations: { uiImageView.alpha = 1.0 })
2. 给UIImageView添加点击手势
// UIImageView默认关闭用户交互,需要手动开启 uiImageView.isUserInteractionEnabled = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onImageViewClicked(_:))) uiImageView.addGestureRecognizer(tapGesture)
3. 实现点击事件处理逻辑
@objc private func onImageViewClicked(_ gesture: UITapGestureRecognizer) { guard let targetImageView = gesture.view as? UIImageView else { return } // 校验当前视图是否有正在运行的动画 guard let animKeys = targetImageView.layer.animationKeys(), !animKeys.isEmpty else { return } // 移除正在运行的淡入动画,避免动画冲突 targetImageView.layer.removeAllAnimations() // 执行淡出动画 UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: { targetImageView.alpha = 0.0 }) { _ in // 淡出完成后可根据需求添加后续处理逻辑,例如移除视图 // targetImageView.removeFromSuperview() } }
注意事项
- 如果需要更精准的动画状态判断,可以通过
targetImageView.layer.presentation()?.alpha获取当前显示层的实际alpha值,和视图的最终alpha值对比判断动画是否运行中 - 淡出动画的时长、缓动效果可根据业务需求自行调整参数
内容的提问来源于stack exchange,提问作者muhammad ali
相关产品推荐
相关产品推荐

