【问题标题】:Keep CABasicAnimation running while moving to another screen移动到另一个屏幕时保持 CABasicAnimation 运行
【发布时间】:2020-09-08 06:06:53
【问题描述】:

我在这里,被听起来像是一个基本问题的困扰......

我制作了一个运行 CABasicAnimation 的简单应用程序:如果我关闭应用程序并重新打开,动画仍在继续(这是完美的),但是如果我在同一个应用程序中更改屏幕然后返回,动画有停止(这很糟糕)。

当用户在同一个应用程序的另一个屏幕上时,任何提示可以帮助我解决问题并保持动画运行?

    override func viewDidLoad() {
    super.viewDidLoad()
    swipeVC()
    myCircle()
}

    // Animated circle
func myCircle() {
    
    // Center the shape
    let center = view.center
    
    // Create back shape
    let backlayer = CAShapeLayer()
    let circulationPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
    
    // Designing the animated circle
    backlayer.path = circulationPath.cgPath
    backlayer.fillColor = UIColor.clear.cgColor
    backlayer.strokeColor = UIColor.red.cgColor
    backlayer.lineWidth = 5
    view.layer.addSublayer(backlayer)
    
    // Designing the animated circle
    shapeLayer.path = circulationPath.cgPath
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = UIColor.green.cgColor
    shapeLayer.lineWidth = 10
    shapeLayer.strokeEnd = 0
    shapeLayer.lineCap = .round
    
    // Add gesture recgnition to activate the circle animation
    view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
    
    // Adding the circle to the main view
    view.layer.addSublayer(shapeLayer)
    
}

【问题讨论】:

    标签: ios swift cabasicanimation


    【解决方案1】:

    据我所知,当应用程序进入后台/导航到其他页面时,IOS会删除动画,这就是你看到“动画已停止”的原因。

    我建议在您离开应用程序或页面时保存动画的当前状态(例如完成率),并在您返回时恢复动画,例如在 viewWillAppear 中或添加一个监听 UIApplicationWillEnterForeground 的观察者.

    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        // listening to when the app will enter foreground
        NotificationCenter.default.addObserver(self, selector: #selector(resumeAnimation), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        ...
        // when come back from other screen
        resumeAnimation()
    }
    
    private resumeAnimation() {
        // re-draw the animation based on stored state
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 2020-12-06
      • 2019-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多