2011-05-12 200 views
0

在我的應用程序在視圖加載後,圖像應該從左到右出現。 我在viewdidloadviewwillappear編寫這些代碼:移動圖像從左到右

 UIImage *image = [UIImage imageNamed:@"PG05(REV).jpg"]; 
     UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 
     for (int i=-1024; i<=0; i++) { 
       NSLog(@"i: %d",i); 
     sleep(5); 
     imageView.frame = CGRectMake(i,0, 1024, 768); 
       NSLog(@"done"); 
     [self.view addSubview:imageView]; 

     } 
     [imageView release]; 

但問題是,它的執行速度比負載鑑於上述代碼之前加載視圖,這樣看來視圖加載和靜態圖像是存在的。 但我的要求是,第一個視圖加載完全,然後圖像應顯示從左到右。

請幫我一把。

回答

2

首先,你不應該在for循環中調用 - (void)addSubview:。你只需要調用一次。其次,如果你想從左到右爲你的imageView設置動畫效果,UIView class爲這個使用塊提供了很好的功能。

您的代碼應該是這樣的:

UIImage *image = [UIImage imageNamed:@"PG05(REV).jpg"]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 
imageView.frame = CGRectMake(-1024, 0, 1024, 768); 
[self.view addSubview:imageView]; 
[imageView release]; //Your imageView is now retained by self.view 

//Animation 
[UIView animateWithDuration:2.0 
       animations:^(void) { 
        imageView.frame = CGRectMake(0, 0, 1024, 768); 
       }]; 

的animateWithDuration:方法將處理動畫計時器你,只是根據自己的需要設置的時間參數。

+0

您好,感謝了很多。你可以告訴我touchBegan(觸摸圖像)時停止動畫的條件/代碼是什麼。 – 2011-05-13 06:27:19

0

您可以使用一個函數並使用計時器方法調用它。

timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(moveImage) userInfo:nil repeats:NO]; 

-(void)moveImage 
{ 
//Your condition 
} 
0

您不應該在循環之前多次執行addSubView:。此外,你應該使用動畫而不是睡眠循環。

實施例:

imageView.frame = CGRectMake(-1024,0, 1024, 768); 
[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration: 5]; 
imageView.frame = CGRectMake(0,0, 1024, 768); 
[UIView commitAnimations];