每次按下按钮时如何创建一个循环来指定不同的动作?

时间:2013-12-08 12:38:50

标签: ios objective-c

我的视图控制器中有一个名为'getQuoteButton'的方法,它是一个连接到按钮的IBAction方法,每次点击按钮我都会得到一个随机引用。

我每次创建一个新引号都会创建一个推送动画,我也想创建一个循环,每次点击按钮我都可以更改动画,但我不知道如何。

这是我的代码(NOViewController),它是一个单一的视图应用程序:

 #import "NOViewController.h"
#include "NOQuotes.h"

@interface NOViewController ()

@end

@implementation NOViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.quotes = [[NOQuotes alloc] init];

    UIImage *background = [UIImage imageNamed:@"albert"];

    [self.backgroundImageView setImage:background];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (IBAction)getQuoteButton
{

    self.quotesLabel.text = [self.quotes getRandomQuote];

    CATransition *animationTran = [CATransition animation];
    [animationTran setType:kCATransitionPush];
    [animationTran setDuration:0.7f];
    [animationTran setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [self.quotesLabel.layer addAnimation:animationTran forKey:@"pushAnimation"];

}


@end

感谢任何帮助,如果您需要任何其他信息,请告知我们,以便您可以提供帮助:)

1 个答案:

答案 0 :(得分:1)

添加整数计数器变量,并在每次按下按钮时递增它。将代码添加到检查计数器的getQuoteButton,并相应地设置动画类型和子类型:

@interface NOViewController () {
    int numClicks; // <<=== Added
}

@end

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.quotes = [[NOQuotes alloc] init];

    UIImage *background = [UIImage imageNamed:@"albert"];

    [self.backgroundImageView setImage:background];
    numClicks = 0; // <<=== Added
}

- (IBAction)getQuoteButton
{

    self.quotesLabel.text = [self.quotes getRandomQuote];

    CATransition *animationTran = [CATransition animation];
    switch (numClicks) { // <<=== Added
        case 0:
            [animationTran setType:kCATransitionPush];
            [animationTran setSubtype:kCATransitionFromRight];
            break;
        case 1:
            [animationTran setType:kCATransitionPush];
            [animationTran setSubtype:kCATransitionFromLeft];
            break;
        case 2:
            [animationTran setType:kCATransitionPush];
            [animationTran setSubtype:kCATransitionFromTop];
            break;
        ... // And so on;
        case 13:
            [animationTran setType:kCATransitionFade];
            // Fade has no subtype
            break;
    }
    numClicks = (numClick+1) % 13; // <<=== Added
    [animationTran setDuration:0.7f];
    [animationTran setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [self.quotesLabel.layer addAnimation:animationTran forKey:@"pushAnimation"];
}

您可以通过创建两个数组或类型/子类型对的数组来缩短此代码,但是在单击时增加成员变量的想法是您实现此目的所需的。