You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift实现View先左向右滑动再左向右消失的动画问题求助

解决Swift中View从左向右滑入再向右滑出的问题

你的代码问题在于初始View的位置和动画方向搞反了:

  • 初始View的x设为0,已经处于屏幕可见区域内
  • 第一个动画用了translationX: -animationView.frame.width,这会让View向左滑出屏幕,和你要的从左向右滑入完全相反

要实现从左向右滑入屏幕,再向右滑出消失的效果,需要调整初始位置和动画的平移方向:

func createAnimationView() -> UIView {
    let screenWidth = UIScreen.main.bounds.width
    // 初始将View放在屏幕左侧外部,完全不可见
    let animationView = UIView(frame: CGRect(x: -screenWidth, y: 0, width: screenWidth, height: 60))
    animationView.backgroundColor = .red
   
    // 第一个动画:从左侧滑入屏幕(平移到x=0的位置)
    UIView.animate(withDuration: 5, animations: {
         animationView.transform = CGAffineTransform(translationX: screenWidth, y: 0)
    }) { _ in
        // 滑入完成后,执行第二个动画:向右滑出屏幕(平移到屏幕右侧外部)
        UIView.animate(withDuration: 5) {
            animationView.transform = CGAffineTransform(translationX: screenWidth * 2, y: 0)
        }
    }
    
    return animationView
}

代码说明:

  • 初始位置:把View的x设为-screenWidth,让它完全处于屏幕左侧之外
  • 第一次动画:通过translationX: screenWidth,将View向右移动整个屏幕宽度,刚好进入屏幕(x=0),实现从左向右滑入
  • 第二次动画:继续向右移动整个屏幕宽度(translationX: screenWidth * 2),让View完全移出屏幕右侧,实现向右滑出消失

如果你更倾向于用frame而不是transform来控制位置,也可以这样写:

func createAnimationView() -> UIView {
    let screenWidth = UIScreen.main.bounds.width
    let animationView = UIView(frame: CGRect(x: -screenWidth, y: 0, width: screenWidth, height: 60))
    animationView.backgroundColor = .red
   
    UIView.animate(withDuration: 5, animations: {
         animationView.frame.origin.x = 0
    }) { _ in
        UIView.animate(withDuration: 5) {
            animationView.frame.origin.x = screenWidth
        }
    }
    
    return animationView
}

两种方式都能实现你要的效果,用transform的好处是不会影响View的布局约束(如果后续用AutoLayout的话)。

内容的提问来源于stack exchange,提问作者Anusha iworld

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 03:35:04