UIButton实现控制动画的开始和停止

本文通过一个僵尸图片动画案例展示了如何在iOS应用中实现动画效果。包括加载图片资源、创建按钮及响应事件、设置动画属性等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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];
    

    }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值