Как изменить частоту анимации UIView в xcode с помощью кнопки - PullRequest
0 голосов
/ 24 марта 2011

Я надеюсь, что кто-то может помочь.У меня есть довольно стандартная анимация UIView, где единственная настоящая анимация - это CGAffineTransformMakeScale, которая установлена ​​в цикле.Я хочу иметь две кнопки: одну, которая увеличивает скорость (или, точнее, уменьшает продолжительность анимации) шкалы, а другую, которая уменьшает скорость (или, точнее, увеличивает продолжительность анимации) шкалы.

Этодаже возможно?Я извиняюсь, если это очевидно, но я новичок и ищу совет - даже если это направленное чтение.Дайте мне знать, если я предоставлю любую дополнительную информацию, чтобы помочь.

Большое спасибо заранее!

Ответы [ 2 ]

1 голос
/ 25 марта 2011

Я не знаю, как изменить текущую анимацию.

Вот код, который, я думаю, делает то, что вы хотите.Он использует кнопки увеличения / уменьшения для изменения ивара animationDuration и вручную зацикливает анимацию как две половины (передняя половина и обратная половина).Каждый раз, когда начинается новая анимация (вперед или назад), она получает значение для animationDuration в этот момент времени, поэтому для коротких анимаций она будет меняться почти мгновенно.Однако он не будет работать хорошо для анимаций с длительной продолжительностью, так как фактически изменяет скорость анимации только в максимальных / минимальных точках анимации.

Вы можете разбить анимацию на еще более мелкие, если хотите обновить чаще - например, разделите ее на 4 вместо 2 (1 -> 1,5, 1,5 -> 2,0, 2,0 -> 1,5, 1,5 -> 1,0) или даже больше, если вам это нужно.

Заголовок (MyViewController.h):

// Define some constants to be edited to suit our needs

#define kAnimationDurationMin 0.1
#define kAnimationDurationDefault 0.4
#define kAnimationDurationMax 2.0
#define kAnimationDurationStep 0.05

@interface MyViewController : UIViewController {
    // The variable to store the target animation duration in
    double animationDuration;
    // Whether the next animation should be a reverse animation or not
    BOOL reverse;
    // The view to be animated, this should be connected in Interface Builder
    IBOutlet UIView *ball;
}

//The method to actually do the animation
-(void)doAnimation;

// These 2 methods should be connected to the 'touch up inside' event of the relevant buttons in Interface Builder
- (IBAction)incButtonPressed:(id)sender;
- (IBAction)decButtonPressed:(id)sender;
@end

Реализация (MyViewController.m):

#import "MyViewController.h"

@implementation MyViewController
-(void)viewDidLoad {
    // If animation duration has not yet been set (it will be zero) then set it to the default.
    if (animationDuration < kAnimationDurationMin) animationDuration = kAnimationDurationDefault;   
    // Start the animation
    [self doAnimation];
}

// This method does the animation
-(void)doAnimation {
    [UIView beginAnimations:@"ball" context:NULL];
    [UIView setAnimationDuration: animationDuration];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
    // Do not repeat
    [UIView setAnimationRepeatCount: 0];
    // Not autoreversing allows us to trigger the animationDuration change twice as frequently.
    [UIView setAnimationRepeatAutoreverses:NO];
    // When the animation is complete, start it again by calling [self doAnimation];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(doAnimation)];
    if (reverse) {
        // Reset to default
        ball.transform = CGAffineTransformMakeScale(1,1);
    } else {
        // Target of forward animation
        ball.transform = CGAffineTransformMakeScale(2,2);       
    }
    // Toggle reverse
    reverse = !reverse;
    [UIView commitAnimations];
}

- (IBAction)incButtonPressed:(id)sender {
    animationDuration += kAnimationDurationStep;
    if (animationDuration > kAnimationDurationMax) animationDuration = kAnimationDurationMax;
}

- (IBAction)decButtonPressed:(id)sender {
    animationDuration -= kAnimationDurationStep;
    if (animationDuration < kAnimationDurationMin) animationDuration = kAnimationDurationMin;
}
@end
0 голосов
/ 24 марта 2011

Вы хотите установить setAnimationDuration класса UIView:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.4];
view.transform = CGAffineTransformMakeScale(0.5, 0.5);
[UIView commitAnimations];

Вот соответствующая документация:

https://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW62

...