我试图通过循环遍历每个对应于颜色的数值列表来更改背景颜色。对于列表中的每个整数,我希望背景更改为该颜色,暂停一秒,然后更改为列表中的下一个颜色。但是,即使整个列表正在迭代,背景颜色似乎也只会变为列表末尾的颜色。我可以做些什么,以便列表中的每个项目的背景都会改变?
当用户按下播放按钮时执行以下代码:
- (IBAction)play:(id)sender {
[self.mem addObject: [NSNumber numberWithInt: arc4random() % 3]];
[UIView animateWithDuration:.5 delay:.5 options:UIViewAnimationOptionTransitionFlipFromRight
animations:
^(void) {
for (int i = 0; i < [self.mem count]; i++) {
if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:0]) {
self.view.backgroundColor = [UIColor blueColor];
} else if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:1]) {
self.view.backgroundColor = [UIColor greenColor];
} else if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:2]) {
self.view.backgroundColor = [UIColor redColor];
} else {
self.view.backgroundColor = [UIColor cyanColor];
}
}
}
completion:
^(BOOL finished) {
if(finished){
}
}];
}
感谢任何帮助!
答案 0 :(得分:0)
-animateWithDuration:options:animations:
将使用您在动画块中最后设置的任何值执行动画 - 它不会在您所做的每项更改上花费 duration
秒。
如果要将背景的动画从一种颜色更改为另一种颜色,则需要按步骤进行操作。使用完成块触发另一个更改(可能只是再次调用-play:
)。您可能希望在ivar中保存一些状态,以便更容易知道您在颜色序列中的位置。
答案 1 :(得分:0)
你非常接近!我已经更新了你的方法,你应该能够简单地复制并粘贴它。请参阅@ Caleb的答案以获得解释。
-(IBAction)play:(id)sender {
static UIColor *color;
// i is the ivar that saves the state in the color sequence
static int i = 0;
if (sender) {
i = 0;
[self.mem addObject:[NSNumber numberWithInt: arc4random() % 3]];
}
if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:0]) {
color = [UIColor blueColor];
} else if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:1]) {
color = [UIColor greenColor];
} else if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:2]) {
color = [UIColor redColor];
} else {
color = [UIColor cyanColor];
}
[UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationOptionTransitionFlipFromRight animations:^{
self.backgroundColor = color;
} completion:^(BOOL finished) {
// Only continue animating if the play button has not been pressed
if (i < self.mem.count - 1) {
i += 1;
// trigger another change by calling play:
[self play:nil];
}
}];
}