#ios #swift #cabasicanimation
#iOS #swift #cabasicanimation
Вопрос:
Вот я и застрял с тем, что звучит как основная проблема…
Я создал простое приложение, которое запускает 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)
}
Ответ №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
}