Skip to content

Instantly share code, notes, and snippets.

Created March 23, 2015 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/2b1e566fe92098437ae0 to your computer and use it in GitHub Desktop.
Save anonymous/2b1e566fe92098437ae0 to your computer and use it in GitHub Desktop.

簡單的來說,因為你的 viewDidLoad 在一般情況下只會被叫一次,所以那段動畫的 code 也只會被執行一次。

如果想要動畫可以重複被觸發,可以使用 NSTimer

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
	NSArray *animationImages = @[
									[UIImage imageNamed:@"1.jpg"],
									[UIImage imageNamed:@"2.jpg"],
									[UIImage imageNamed:@"3.jpg"],
									[UIImage imageNamed:@"4.jpg"]
								];
   
	UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300, 300)];
	imageView.animationImages = animationImages ;
	imageView.animationRepeatCount = 0;
	imageView.animationDuration= 12.0;
	[imageView startAnimating];
	[self.view addSubview:imageView];
	
	// 當圖片改變時呼叫執行動畫的 method => scaleView:
	[[NSTimer scheduledTimerWithTimeInterval:12.0/animationImages.count
                                      target:self
                                    selector:@selector(scaleView:)
                                    userInfo:@{
                                               @"view": imageView
                                               }
                                     repeats:YES] fire];
}

- (void)scaleView:(NSTimer *)timer {
    UIImageView *view = [timer.userInfo objectForKey:@"view"];
    view.frame = CGRectMake(150, 150, 20, 20);
    CGPoint center = view.center;
    [UIView animateWithDuration: 1.0f
                     animations:^{
                         view.frame = CGRectMake(10, 10, 300, 300);
                         view.center = center;
                     }];

}

P.S.

一般來說比較適當的做法是當 imageViewimage 改變時利用 KVO去觸發動畫。

但是剛剛試了一下,如果使用 UIImageView 的 animation 似乎是沒有辦法偵測到 image 這個 property 的改變的(不知道為什麼,還請高手指點)。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment