最近做的東西中,要為一個有特定圖片的按鈕添加旋轉動畫,Demo代碼如下:
#import "ViewController.h" @interface ViewController () { BOOL flag; } @property (strong, nonatomic) UIImageView *imageView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; flag = YES; self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)]; UIImage *aImage = [UIImage imageNamed:@"down.png"]; [_imageView setImage:aImage]; _imageView.center = self.view.center; [self.view addSubview:_imageView]; UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; [button setTitle:@"旋轉" forState:UIControlStateNormal]; [button addTarget:self action:@selector(rotate:) forControlEvents:UIControlEventTouchUpInside]; button.frame = CGRectMake(110, 400, 100, 44); [self.view addSubview:button]; } - (void)rotate:(id)sender { if (flag) { [UIView animateWithDuration:0.5 animations:^{ _imageView.transform = CGAffineTransformMakeRotation(M_PI); } completion:^(BOOL finished) { flag = NO; }]; } else { [UIView animateWithDuration:0.5 animations:^{ _imageView.transform = CGAffineTransformMakeRotation(0); } completion:^(BOOL finished) { flag = YES; }]; } } @end
運行時真機設備和模擬器的按鈕旋轉動畫中,方向可能有點不同,有點奇怪。
其中一些運行截圖如下:
Demo地址:點擊打開鏈接