Rotate UIImageView clockwise

后端 未结 4 1783
再見小時候
再見小時候 2021-02-03 11:48

This should be simple, but I\'m having trouble rotating a UIImageView a full 360 degrees, repeated forever.

[UIView animateWithDuration:0.5 delay:0          


        
4条回答
  •  死守一世寂寞
    2021-02-03 12:35

    I encountered the same issue a while ago. I do not remember the reason for that issue, but this is my solution:

    /**
     * Incrementally rotated the arrow view by a given angle.
     *
     * @param degrees Angle in degrees.
     * @param duration Duration of the rotation animation.
     */
    - (void)rotateArrowViewByAngle:(CGFloat)degrees
                      withDuration:(NSTimeInterval)duration {
    
        CABasicAnimation *spinAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        spinAnimation.fromValue = [NSNumber numberWithFloat:self.currentAngle / 180.0 * M_PI];
        spinAnimation.toValue = [NSNumber numberWithFloat:degrees / 180.0 * M_PI];
        spinAnimation.duration = duration;
        spinAnimation.cumulative = YES;
        spinAnimation.additive = YES;
        spinAnimation.removedOnCompletion = NO;
        spinAnimation.delegate = self;
        spinAnimation.fillMode = kCAFillModeForwards;
    
        [self.arrowView.layer addAnimation:spinAnimation forKey:@"spinAnimation"];
    
        self.currentAngle = degrees;
    }
    

    and then you can use the delegate methods

    - (void)animationDidStart:(CAAnimation *)theAnimation
    - (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
    

    to rotate keep it rotating. Also, degree and duration parameters can be really high numbers... if this is enough.

    UPDATE:
    As stated by yinkou,

    spinAnimation.repeatCount = HUGE_VALF;     // HUGE_VALF is defined in math.h so import it 
    

    is way better that restarting the animation in the delegate.

    PLEASE NOTE:
    self.currentAngle is a property remembering the current final rotation.
    I needed that to make the view rotate left and right way around.

提交回复
热议问题