首页 > 代码库 > iOS 特定图片的按钮的旋转动画

iOS 特定图片的按钮的旋转动画

最近做的东西中,要为一个有特定图片的按钮添加旋转动画,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地址:点击打开链接