想象一下老式时尚弹球机(或类似机器),机器顶部记分牌面板两侧各有三个灯泡。灯泡编号为1-6
我希望能够调用一个方法,将灯亮起0.5秒然后再关闭传递一个数字数组作为灯应该闪烁的序列
我写下面的内容确实有效,但看起来非常低效且不必要地冗长。我认为使用计时器会更好,但我不知道如何使用我的“序列”数组
有更好的方法吗?
- (IBAction)testLights:(id)sender {
NSArray *sequence = [[NSArray alloc] initWithObjects: [NSNumber numberWithInt:0], [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], [NSNumber numberWithInt:4],[NSNumber numberWithInt:5],nil];
[self setLights:sequence];
}
- (void)setLights:(NSArray *)sequence {
UIImageView *light=[lgtArray objectAtIndex: [[sequence objectAtIndex:0]integerValue]];
light.alpha = 0;
[UIView animateWithDuration:0.3f
animations:^{
light.alpha = 1;
}completion:^(BOOL finished){
//new annimation
light.alpha = 0;
UIImageView *light=[lgtArray objectAtIndex: [[sequence objectAtIndex:1]integerValue]];
[UIView animateWithDuration:0.3f
animations:^{
light.alpha = 1;
}completion:^(BOOL finished){
//new annimation
light.alpha = 0;
UIImageView *light=[lgtArray objectAtIndex: [[sequence objectAtIndex:2]integerValue]];
[UIView animateWithDuration:0.3f
animations:^{
light.alpha = 1;
}completion:^(BOOL finished){
//new annimation
light.alpha = 0;
UIImageView *light=[lgtArray objectAtIndex: [[sequence objectAtIndex:3]integerValue]];
[UIView animateWithDuration:0.3f
animations:^{
light.alpha = 1;
}completion:^(BOOL finished){
//new annimation
light.alpha = 0;
UIImageView *light=[lgtArray objectAtIndex: [[sequence objectAtIndex:4]integerValue]];
[UIView animateWithDuration:0.3f
animations:^{
light.alpha = 1;
}completion:^(BOOL finished){
//new annimation
light.alpha = 0;
UIImageView *light=[lgtArray objectAtIndex: [[sequence objectAtIndex:5]integerValue]];
[UIView animateWithDuration:0.3f
animations:^{
light.alpha = 1;
}completion:^(BOOL finished){
light.alpha = 0;
}];
}];
}];
}];
}];
}];
}
答案 0 :(得分:1)
这可以通过使函数递归来实现。我建议你将序列对象作为NSMutableArray传递。
- (void)setLights:(NSMutableArray *)sequence {
if ([sequence count] > 0)
{
UIImageView *light=[lgtArray objectAtIndex: [[sequence objectAtIndex:0]integerValue]];
[sequence removeObjectAtIndex:0];
light.alpha = 0;
[UIView animateWithDuration:0.3f
animations:^{
light.alpha = 1;
}completion:^(BOOL finished){
[self setLights:sequence];
}];
}
}
此功能具有额外的优势,能够处理任意数字的序列,而不仅仅是6。