我正在尝试创建一个应用,当您点按一个按钮时,它将转到动画中的下一帧。
我有8个图像文件,当我按下按钮时我想要显示第一个图像,当我再次按下按钮时,我希望第二个图像替换第一个图像,依此类推。
我在想这样的事情:
-(IBAction)buttonPressDoStuff:(id)sender {
imageThing.image = [UIImage imageNamed:@"image1.png"];
imageThing.image = [UIImage imageNamed:@"image2.png"];
imageThing.image = [UIImage imageNamed:@"image3.png"];
imageThing.image = [UIImage imageNamed:@"image4.png"];
}
并以某种方式使这一切都在每次按下时连续工作。
我在目标c上相当新,所以任何帮助都会非常感激。
任何人都可以抛出一些示例代码来执行此操作吗?
答案 0 :(得分:1)
让我们考虑一下。如果你想按顺序执行某些操作,那听起来就像是数组的工作。那你怎么看待这个:
在.h文件中,添加以下实例变量:
NSMutableArray* picturesArray;
NSInteger counter;
现在在你的.m文件中,在你的类'init方法:
中//this loop will fill your array with the pictures
for(int idx = 0; idx < NUMBER_OF_PICTURES; idx++) {
//IMPORTANT: this assumes that your pictures' names start with
//'image0.png` for the first image, then 'image1.png`, and so on
//if your images' names start with 'image1.png' and then go up, then you
//should change the 'int idx = 0' declaration in the for loop to 'int idx = 1'
//so the loop will start at 0. You will then need to change the condition
//to 'idx < (NUMBER_OF_PICTURES + 1)' to accomodate the last image
NSString* temp = [NSString stringWithFormat:@"image%i.png", idx];
UIImage* tempImage = [UIImage imageNamed:temp];
[picturesArray addObject:tempImage];
}
并在您的buttonPressDoStuff:
方法中:
//this method will move to the next picture in the array each time it is pressed
-(IBAction)buttonPressDoStuff:(id)sender {
if(counter < [pictureArray count]) {
imageThing.image = [picturesArray objectAtIndex:counter];
counter++;
}
}
您的init
方法应如下所示:
- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self) {
//do setup here
for(int idx = 0; idx < NUMBER_OF_PICTURES; idx++) {
NSString* temp = [NSString stringWithFormat:@"image%i.png", idx];
UIImage* tempImage = [UIImage imageNamed:temp];
[picturesArray addObject:tempImage];
}
}
//it is important that you return 'self' no matter what- if you don't,
//you will get the 'control reached end of non-void method' warning
return self;
}