CALayer Rotation animation is not working on presented ViewController - ios

I have two view controllers (i.e firstVC and secondVC). I am presenting secondVC over firstVC and trying to achieve rotation animation but it's not working, I have tried running animation on the main thread with some delay but it's giving weird behavior. Following is the code I am using to rotate the view.
extension UIView {
private static let kRotationAnimationKey = "rotationanimationkey"
func rotate(duration: Double = 1, delay: Int = 0) {
if layer.animation(forKey: UIView.kRotationAnimationKey) == nil {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = Float.pi * 2.0
rotationAnimation.duration = duration
rotationAnimation.repeatCount = Float.infinity
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(delay)) {
self.layer.add(rotationAnimation, forKey: UIView.kRotationAnimationKey)
}
}
}
func stopRotating() {
if layer.animation(forKey: UIView.kRotationAnimationKey) != nil {
layer.removeAnimation(forKey: UIView.kRotationAnimationKey)
}
}}
Note: By pushing 'secondVC' animation is working properly. But I wanted to present 'secondVC'.
I am not getting what's happening during the presentation of the view controller and rotation animation.
Please let me know if you find any solution.

For using custom presentation transition you have to confirm to UIViewControllerTransitioningDelegate. UIKit always call animationController(forPresented:presenting:source:) to see if a UIViewControllerAnimatedTransitioning is returned. If it is returning nil then default animation is used.

Related

Interactive View Controller Transition - Weird behavior (stuck in the transition)

I'm trying to implement a custom pan gesture to interactively transition to a new view controller. The way it works is that I have a button (labeled "Template Editor", see below) on which you can start a pan to move the current view controller to the right, revealing the new view controller next to it (I've recorded my problem, see below).
Everything is working but there is a bug that I don't understand at all:
Sometimes, when I just swipe over the button (triggering a pan gesture) then lift my finger again (touch down -> fast, short swipe to the right -> touch up) the interactive transition glitches out. It starts to very slowly complete the transition and afterwards, I cannot dismiss the presented view controller, nor can I present anything on that presented view controller.
I have no idea why. Here's my code:
First, the UIViewControllerAnimatedTransitioning class. It's implemented using UIViewPropertyAnimator and just adds the animation using transform:
class MovingTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
enum Direction {
case left, right
}
// MARK: - Properties
// ========== PROPERTIES ==========
private var animator: UIViewImplicitlyAnimating?
var duration = 0.6
var presenting = true
var shouldAnimateInteractively: Bool = false
public var direction: Direction = .left
private var movingMultiplicator: CGFloat {
return direction == .left ? -1 : 1
}
// ====================
// MARK: - Initializers
// ========== INITIALIZERS ==========
// ====================
// MARK: - Overrides
// ========== OVERRIDES ==========
// ====================
// MARK: - Functions
// ========== FUNCTIONS ==========
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let animator = interruptibleAnimator(using: transitionContext)
animator.startAnimation()
}
func interruptibleAnimator(using transitionContext: UIViewControllerContextTransitioning) -> UIViewImplicitlyAnimating {
// If the animator already exists, return it (important, see documentation!)
if let animator = self.animator {
return animator
}
// Otherwise, create the animator
let containerView = transitionContext.containerView
let fromView = transitionContext.view(forKey: .from)!
let toView = transitionContext.view(forKey: .to)!
if presenting {
toView.frame = containerView.frame
toView.transform = CGAffineTransform(translationX: movingMultiplicator * toView.frame.width, y: 0)
} else {
toView.frame = containerView.frame
toView.transform = CGAffineTransform(translationX: -movingMultiplicator * toView.frame.width, y: 0)
}
containerView.addSubview(toView)
let animator = UIViewPropertyAnimator(duration: duration, dampingRatio: 0.9, animations: nil)
animator.addAnimations {
if self.presenting {
toView.transform = .identity
fromView.transform = CGAffineTransform(translationX: -self.movingMultiplicator * toView.frame.width, y: 0)
} else {
toView.transform = .identity
fromView.transform = CGAffineTransform(translationX: self.movingMultiplicator * toView.frame.width, y: 0)
}
}
animator.addCompletion { (position) in
// Important to set frame above (device rotation will otherwise mess things up)
toView.transform = .identity
fromView.transform = .identity
if !transitionContext.transitionWasCancelled {
self.shouldAnimateInteractively = false
}
self.animator = nil
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
self.animator = animator
return animator
}
// ====================
}
Here's the part that adds the interactivity. It's a method that's being called by a UIPanGestureRecognizer I added to the button.
public lazy var transitionAnimator: MovingTransitionAnimator = MovingTransitionAnimator()
public lazy var interactionController = UIPercentDrivenInteractiveTransition()
...
#objc private func handlePan(pan: UIPanGestureRecognizer) {
let translation = pan.translation(in: utilityView)
var progress = (translation.x / utilityView.frame.width)
progress = CGFloat(fminf(fmaxf(Float(progress), 0.0), 1.0))
switch pan.state {
case .began:
// This is a flag that helps me distinguish between when a user taps on the button and when he starts a pan
transitionAnimator.shouldAnimateInteractively = true
// Just a dummy view controller that's dismissing as soon as its been presented (the problem occurs with every view controller I use here)
let vc = UIViewController()
vc.view.backgroundColor = .red
vc.transitioningDelegate = self
present(vc, animated: true, completion: {
self.transitionAnimator.shouldAnimateInteractively = false
vc.dismiss(animated: true, completion: nil)
})
case .changed:
interactionController.update(progress)
case .cancelled:
interactionController.cancel()
case .ended:
if progress > 0.55 || pan.velocity(in: utilityView).x > 600
interactionController.completionSpeed = 0.8
interactionController.finish()
} else {
interactionController.completionSpeed = 0.8
interactionController.cancel()
}
default:
break
}
}
I also implemented all the necessary delegate methods:
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transitionAnimator.presenting = true
return transitionAnimator
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transitionAnimator.presenting = false
return transitionAnimator
}
func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
guard let animator = animator as? MovingTransitionAnimator, animator.shouldAnimateInteractively else { return nil }
return interactionController
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
guard let animator = animator as? MovingTransitionAnimator, animator.shouldAnimateInteractively else { return nil }
return interactionController
}
That's it. There's no more logic behind it (I think; if you need more information, please tell me), but it still has this bug. Here's a recording of the bug. You can't really see my touch but all I'm doing is touching down -> fast, shortly swiping to the right -> touching up. And after this really slow transition has finished, I can't dismiss the red view controller. It's stuck there:
Here's what's even stranger:
Neither interactionController.finish() nor interactionController.cancel() is being called when this occurs (at least not from within my handlePan(_:)method).
I checked the view hierarchy in Xcode after this bug occurred and I got this:
First, it's seemingly stuck in the transition (everything is still inside UITransitionView).
Second, on the left hand side you see the views of the first view controller(the one I start the transition from). However, on the image there only is the red view controller visible, the one that was about to be presented.
Do you have any idea what's going on? I've been trying to figure this out for the past 3 hours but I can't get get it to work properly. I'd appreciate any help
Thank you!
EDIT
Okay, I found a way to reproduce it 100% of the time. I also created an isolated project demonstrating the problem (it's a little differently structured because I tried many things but the result is still exactly the same)
Here's the project: https://github.com/d3mueller/InteractiveTransitionDemo2
How to reproduce the problem:
Swipe from right to left and then quickly from left to right. This will trigger the bug.
Also, a similar bug will appear, when you swipe from right to left very fast multiple times. Then it will actually run the transition and finish it correctly (but it shouldn't even start because moving from right to left keeps the progress at 0.0)
You might try setting:
/// Set this to NO in order to start an interruptible transition non
/// interactively. By default this is YES, which is consistent with the behavior
/// before 10.0.
#property (nonatomic) BOOL wantsInteractiveStart NS_AVAILABLE_IOS(10_0);
to NO on your interactionController
Good luck and curious to hear if you figure it out.

Start/stop image view rotation animations

I have a start/stop button and an image view which I want to rotate.
When I press the button I want the to start rotating and when I press the button again the image should stop rotating. I am currently using an UIView animation, but I haven't figured out a way to stop the view animations.
I want the image to rotate, but when the animation stops the image shouldn't go back to the starting position, but instead continue the animation.
var isTapped = true
#IBAction func startStopButtonTapped(_ sender: Any) {
ruotate()
isTapped = !isTapped
}
func ruotate() {
if isTapped {
UIView.animate(withDuration: 5, delay: 0, options: .repeat, animations: { () -> Void in
self.imageWood.transform = self.imageWood.transform.rotated(by: CGFloat(M_PI_2))
}, completion: { finished in
ruotate()
})
} }
It is my code, but it doesn't work like I aspect.
Swift 3.x
Start Animation
let rotationAnimation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: .pi * 2.0)
rotationAnimation.duration = 0.5;
rotationAnimation.isCumulative = true;
rotationAnimation.repeatCount = .infinity;
self.imageWood?.layer.add(rotationAnimation, forKey: "rotationAnimation")
Stop animation
self.imageWood?.layer.removeAnimation(forKey: "rotationAnimation")
Swift 2.x
Start Animation
let rotationAnimation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(double: M_PI * 2.0)
rotationAnimation.duration = 1;
rotationAnimation.cumulative = true;
rotationAnimation.repeatCount = .infinity;
self.imageWood?.layer.addAnimation(rotationAnimation, forKey: "rotationAnimation")
Stop animation
self.imageWood?.layer.removeAnimation(forKey: "rotationAnimation")
If you use UIView Animation the OS still creates one or more CAAnimation objects. Thus, to stop a UIView animation you can still use:
myView.layer.removeAllAnimations()
Or if you create the animation using a CAAnimation on a layer:
myLayer.removeAllAnimations()
In either case, you can capture the current state of the animation and set that as the final state before removing the animation. If you're doing an animation on a view's transform, like in this question, that code might look like this:
func stopAnimationForView(_ myView: UIView) {
//Get the current transform from the layer's presentation layer
//(The presentation layer has the state of the "in flight" animation)
let transform = myView.layer.presentationLayer.transform
//Set the layer's transform to the current state of the transform
//from the "in-flight" animation
myView.layer.transform = transform
//Now remove the animation
//and the view's layer will keep the current rotation
myView.layer.removeAllAnimations()
}
If you're animating a property other than the transform you'd need to change the code above.
using your existing code you can achieve it the following way
var isTapped = true
#IBAction func startStopButtonTapped(_ sender: Any) {
ruotate()
isTapped = !isTapped
}
func ruotate() {
if isTapped {
let rotationAnimation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: Double.pi * 2.0)
rotationAnimation.duration = 1;
rotationAnimation.isCumulative = true;
rotationAnimation.repeatCount = HUGE;
self.imageWood?.layer.add(rotationAnimation, forKey: "rotationAnimation")
}else{
self.imageWood?.layer.removeAnimation(forKey: "rotationAnimation")
}
}
Apple added a new class, UIViewPropertyAnimator, to iOS 10. A UIViewPropertyAnimator allows you to easily create UIView-based animations that can be paused, reversed, and scrubbed back and forth.
If you refactor your code to use a A UIViewPropertyAnimator you should be able to pause and resume your animation.
I have a sample project on Github that demonstrates using a UIViewPropertyAnimator. I suggest taking a look at that.
Your code make the image rotate for 2PI angle, but if you click on the button while the rotation is not ended, the animation will finish before stop, that's why it comes to the initial position.
You should use CABasicAnimation to use a rotation that you can stop at anytime keeping the last position.

How to animate tabbar badge count in swift

I want to animate badge count over tabbar something like Bouncing Animation . Has anyone implemented it with native UITabBarController . i am not using any third party class for adding UITabBarController in my project.
i do some thing like this before i will share the code with you
first i create two functions
first one is :
func loopThrowViews(view:UIView){
for subview in (view.subviews){
let type = String(describing: type(of: subview))
print(type)
if type == "_UIBadgeView" {
print("this is BadgeView")
animateView(view: subview)
}
else {
loopThrowViews(view:subview)
}
}
}
this function take view and loop throw all its subViews until it find the badge View then it's call the animate method this one
func animateView(view:UIView){
let shakeAnimation = CABasicAnimation(keyPath: "position")
shakeAnimation.duration = 0.05
shakeAnimation.repeatCount = 50
shakeAnimation.autoreverses = true
shakeAnimation.fromValue = NSValue(cgPoint: CGPoint(x:view.center.x - 10, y:view.center.y))
shakeAnimation.toValue = NSValue(cgPoint: CGPoint(x:view.center.x + 10, y:view.center.y))
view.layer.add(shakeAnimation, forKey: "position")
}
You can replace the code at this method with your own animation
all what you need is to call this method like this when ever you want to animate the badge
loopThrowViews(view: self.tabBarController!.tabBar)
the result will be like this
full example here https://github.com/AliAdam/AnimateTabbarBadgeView

'Press and hold' animation without NSTimer

Update: The NSTimer approach works now, but comes with a huge performance hit. The question is now narrowed down to an approach without NSTimers.
I'm trying to animate a 'Press and hold' interactive animation. After following a load of SO answers, I've mostly followed the approach in Controlling Animation Timing by #david-rönnqvist. And it works, if I use a Slider to pass the layer.timeOffset.
However, I can't seem to find a good way to continuously update the same animation on a press and hold gesture. The animation either doesn't start, only shows the beginning frame or at some points finishes and refuses to start again.
Can anyone help with achieving the following effect, without the horrible NSTimer approach I'm currently experimenting with?
On user press, animation starts, circle fills up.
While user holds (not necessarily moving the finger), the animation should continue until the end and stay on that frame.
When user lifts finger, the animation should reverse, so the circle is empties again.
If the user lifts his finger during the animation or presses down again during the reverse, the animation should respond accordingly and either fill or empty from the current frame.
Here's a Github repo with my current efforts.
As mentioned, the following code works well. It's triggered by a slider and does its job great.
func animationTimeOffsetToPercentage(percentage: Double) {
if fillShapeLayer == nil {
fillShapeLayer = constructFillShapeLayer()
}
guard let fillAnimationLayer = fillShapeLayer, let _ = fillAnimationLayer.animationForKey("animation") else {
print("Animation not found")
return
}
let timeOffset = maximumDuration * percentage
print("Set animation to percentage \(percentage) with timeOffset: \(timeOffset)")
fillAnimationLayer.timeOffset = timeOffset
}
However, the following approach with NSTimers works, but has an incredible performance hit. I'm looking for an approach which doesn't use the NSTimer.
func beginAnimation() {
if fillShapeLayer == nil {
fillShapeLayer = constructFillShapeLayer()
}
animationTimer?.invalidate()
animationTimer = NSTimer.schedule(interval: 0.1, repeats: true, block: { [unowned self] () -> Void in
if self.layer.timeOffset >= 1.0 {
self.layer.timeOffset = self.maximumDuration
}
else {
self.layer.timeOffset += 0.1
}
})
}
func reverseAnimation() {
guard let fillAnimationLayer = fillShapeLayer, let _ = fillAnimationLayer.animationForKey("animation") else {
print("Animation not found")
return
}
animationTimer?.invalidate()
animationTimer = NSTimer.schedule(interval: 0.1, repeats: true, block: { [unowned self] () -> Void in
if self.layer.timeOffset <= 0.0 {
self.layer.timeOffset = 0.0
}
else {
self.layer.timeOffset -= 0.1
}
})
}
When you use slider you use fillAnimationLayer layer for animation
fillAnimationLayer.timeOffset = timeOffset
However, in beginAnimation and reverseAnimation functions you are using self.layer.
Try to replace self.layer.timeOffset with self.fillShapeLayer!.timeOffset in your timer blocks.
The solution is two-fold;
Make sure the animation doesn't remove itself on completion and keeps its final frame. Easily accomplished with the following lines of code;
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
The hard part; you have to remove the original animation and start a new, fresh reverse animation that begins at the correct point. Doing this, gives me the following code;
func setAnimation(layer: CAShapeLayer, startPath: AnyObject, endPath: AnyObject, duration: Double)
{
// Always create a new animation.
let animation: CABasicAnimation = CABasicAnimation(keyPath: "path")
if let currentAnimation = layer.animationForKey("animation") as? CABasicAnimation {
// If an animation exists, reverse it.
animation.fromValue = currentAnimation.toValue
animation.toValue = currentAnimation.fromValue
let pauseTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
// For the timeSinceStart, we take the minimum from the duration or the time passed.
// If not, holding the animation longer than its duration would cause a delay in the reverse animation.
let timeSinceStart = min(pauseTime - startTime, currentAnimation.duration)
// Now convert for the reverse animation.
let reversePauseTime = currentAnimation.duration - timeSinceStart
animation.beginTime = pauseTime - reversePauseTime
// Remove the old animation
layer.removeAnimationForKey("animation")
// Reset startTime, to be when the reverse WOULD HAVE started.
startTime = animation.beginTime
}
else {
// This happens when there is no current animation happening.
startTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
animation.fromValue = startPath
animation.toValue = endPath
}
animation.duration = duration
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
layer.addAnimation(animation, forKey: "animation")
}
This Apple article explains how to do a proper pause and resume animation, which is converted to use with the reverse animation.

Animation not working when use POPDecayAnimation

I make dropping down animation for changing views. When I use POPSpringAnimation all working correctly. But when I change POPSpringAnimation to POPDecayAnimation nothing happens and in debug output I see this message:
ignoring to value on decay animation <POPDecayAnimation:0x7f9f2b5c8700; from = null; to = null; deceleration = 0.998000>
Code:
func switchViewController(from: UIViewController?, toViewController to: UIViewController?, animated: Bool) {
if animated {
to!.view.frame = self.view.frame
// Not working when call trulySwitchViewController
self.addChildViewController(to!)
self.view.insertSubview(to!.view, belowSubview: from!.view)
to!.didMoveToParentViewController(self)
// Calculate new x coord
var frame = from!.view.frame
frame.origin.y += frame.size.height
// POPDecayAnimation not working here
var animation = POPDecayAnimation()
animation.property = POPAnimatableProperty.propertyWithName(kPOPViewFrame) as POPAnimatableProperty
animation.toValue = NSValue(CGRect:frame)
animation.completionBlock = {
(_, _) in
self.trulySwitchViewController(from, toViewController: nil)
}
from!.view.pop_addAnimation(animation, forKey: "dropDown")
} else {
to?.view.frame = self.view.frame
self.trulySwitchViewController(from, toViewController: to)
}
}
For a decay animation you need to set the velocity property, this then decays to zero based on the deceleration property. So, the to property is not needed, the end state is determined based on the start position, velocity and deceleration.
You also need to animate the layer position not the view frame. So something like this should work...
var animation = POPDecayAnimation()
animation.property = POPAnimatableProperty.propertyWithName(kPOPLayerPosition) as POPAnimatableProperty
from!.view.layer.pop_addAnimation(animation, forKey: "dropDown")

Resources