2010-09-03 50 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];