UIButton實現控制動畫的開始和停止
阿新 • • 發佈:2019-01-06
import “ViewController.h”
@interface ViewController ()
@property(nonatomic,retain)UIImageView *imageView;
@end
@implementation ViewController
- (void)dealloc
{
self.imageView = nil;
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor]; UIImage *image = [UIImage imageNamed:@"Zombie0.tiff"]; self.imageView = [[UIImageView alloc]initWithImage:image]; _imageView.frame = CGRectMake(60, 60, 160, 240); [self.view addSubview:_imageView]; [_imageView release]; UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; button.backgroundColor = [UIColor brownColor]; button.frame = CGRectMake(140, 360, 40, 30); [button setTitle:@"開始" forState:UIControlStateNormal]; [self.view addSubview:button]; //新增關聯事件 [button addTarget:self action:@selector(controlAnimation:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)controlAnimation:(UIButton *)sender{
//取出button上的title NSString *title = [sender titleForState:UIControlStateNormal]; //判斷title是否和@"開始"相同,相同則開始動畫,並修改標題為@"停止",如果不相同,則停止動畫,並修改標題為@"開始" if ([title isEqualToString:@"開始"]) { [self aninationWithImageName:@"Zombie"andImageCount:21]; [sender setTitle:@"停止" forState:UIControlStateNormal]; } else { [_imageView stopAnimating]; [sender setTitle:@"開始" forState:UIControlStateNormal]; }
}
(void)aninationWithImageName:(NSString *)names andImageCount:(int )count{
if (_imageView.isAnimating) {
return;
}
NSMutableArray *imageArray = [NSMutableArray array];for (int i = 0; i < count; i++) {
NSString *name = [NSString stringWithFormat:@"%@%d.tiff",names,i]; UIImage *image = [UIImage imageNamed:name]; [imageArray addObject:image]; _imageView.animationImages = imageArray; _imageView.animationDuration = imageArray.count * 0.03; _imageView.animationRepeatCount = 0; [_imageView startAnimating];
}
}