2010-09-03 54 views
0

我下面的循环中添加UIViews到上海华:如何发送时间延迟的消息,一个UIView上的计时器

int xValue = 0 ; 
int yValue = 10; 
for (NSString *element in characters) { 
    UIView *newCharView = [[MyChar alloc] initWithFrame:CGRectMake(xValue,yValue,100,100)]; 
    [(MyChar *)newCharView initLayers:element]; 
    [[self view] addSubview:newCharView]; 
    [newCharView autorelease]; 

    if (xValue <= 240) { 
     xValue+=22; 
    } else { 
     xValue = 0; 
     yValue += 22; 
    } 

} 

MYChar包含触发动画的方法。我希望在我的循环中按顺序调用该方法,延迟时间例如为0.2秒。我怎样才能做到这一点?我尝试延迟动画本身,但显然只是在所有UIViews中获得相同的延迟。

回答

2

你可以尝试使用这样的事情:

int xValue = 0 ; 
int yValue = 10; 
double delay = 0.2; 
for (NSString *element in characters) { 
    UIView *newCharView = [[MyChar alloc] initWithFrame:CGRectMake(xValue,yValue,100,100)]; 
    [self performSelector:@selector(delayedInitView:) withObject:element afterDelay:delay]; 

    if (xValue <= 240) { 
     xValue+=22; 
    } else { 
     xValue = 0; 
     yValue += 22; 
    } 
    delay += 0.2; 

} 

-(void) delayedInitView: (id) element { 
    [(MyChar *) newCharView initLayers: element]; 
    [[self view] addSubview: newCharView]; 
    [newCharView autorelease]; 
} 

你将不得不与实验,因为我不知道你想什么做实现。

编辑: 哎哟,这绝对不是一个很好的方式去与如此多的意见。你可以尝试使用一个后台循环来初始化它们。 我肯定得想好了一个可爱的更多,如果我个人面对这个问题,但这里有一个简单的建议,你将不得不调整它您的需要和可能采取它的线程/内存管理安全的护理:

[self performSelectorInBackground:@(backgroundInitViews:) withObject:characters] 

-(void) backgroundInitViews: (NSArray*) elements { 
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; 
    int xValue = 0 ; 
    int yValue = 10; 
    for (NSString *element in elements) { 
     UIView *newCharView = [[MyChar alloc] initWithFrame:CGRectMake(xValue,yValue,100,100)]; 
     [(MyChar *) newCharView initLayers: element]; 
     [[self view] addSubview: newCharView]; 
     [newCharView autorelease]; 


     if (xValue <= 240) { 
      xValue+=22; 
     } else { 
      xValue = 0; 
      yValue += 22; 
     } 
     [NSThread sleepForTimeInterval:0.2]; 
    } 
    [pool drain]; 
} 
+0

谢谢你的工作。在模拟器中性能很好,但在设备(iPhone4)上可怕。我不是说它的代码,但如果我添加140个UIViews,每个包含30层,有没有更好的方法来做到这一点? – codecowboy 2010-09-04 04:57:35

+0

我刚刚编辑了我的回复,这应该会提高很多。 – Mayjak 2010-09-04 19:39:06

0

这给一试:

[self performSelector:@selector(postAnimationMethod) withObject:self afterDelay:0.2];