版本记录
版本号 | 时间 |
---|---|
V1.0 | 2017.06.14 |
前言
大家在用非智能机的时候,里面的几个游戏都屈指可数,俄罗斯方框、贪吃蛇、Tom猫等等,这里Tom猫就是大家非常熟悉的一款小应用游戏,这里以OC代码实现其简单动画效果。
详情
下面就先看代码的组织结构吧。
下面还是直接看代码
1. JJTomVC.m
#import "JJTomVC.h"
#define kJJTomVCColumnNumber 2
@interface JJTomVC ()
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) NSDictionary *animationDict;
@end
@implementation JJTomVC
#pragma mark - Override Base Function
- (void)viewDidLoad
{
[super viewDidLoad];
self.animationDict = [NSDictionary dictionary];
[self loadDict];
[self setupUI];
}
#pragma mark - Object Private Function
- (void)setupUI
{
self.view.backgroundColor = [UIColor whiteColor];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.frame];
self.imageView = imageView;
self.imageView.image = [UIImage imageNamed:@"tom"];
[self.view addSubview:imageView];
for (NSString *temp in self.animationDict) {
[self addButtonsWithKey:temp];
}
}
- (void)addButtonsWithKey:(NSString *)key
{
static NSInteger i = 0;
NSInteger btnW = 30 ,btnH = 30, btnX ,btnY, spaceX = 250, spaceY = 200;
UIButton *button = [[UIButton alloc] init];
[button setTitle:key forState:UIControlStateNormal];
button.titleLabel.textAlignment = NSTextAlignmentCenter;
[button setImage:[UIImage imageNamed:key] forState:UIControlStateNormal];
btnX = 30 + spaceX * (i % kJJTomVCColumnNumber);
btnY = 50 + spaceY * (i / kJJTomVCColumnNumber);
button.frame = CGRectMake(btnX, btnY, btnW, btnH);
i++;
[button addTarget:self action:@selector(playAnimationWithkey:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)loadDict
{
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"tom.plist" withExtension:nil]];
self.animationDict = dict;
}
#pragma mark - Action && Notification
- (void)playAnimationWithkey:(UIButton *)button
{
NSMutableArray *animationArr = [NSMutableArray array];
for (NSInteger i = 0; i < [self.animationDict[button.titleLabel.text] integerValue]; i++) {
NSString *imageName = [NSString stringWithFormat:@"%@_%02zd",button.titleLabel.text,i];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageName ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
[animationArr addObject:image];
}
self.imageView.animationImages = animationArr;
self.imageView.animationRepeatCount = 1;
self.imageView.animationDuration = 2;
[self.imageView startAnimating];
}
@end
代码中有一处要特别注意:static NSInteger i = 0;,这个必须要有static来修饰,要不每次循环过来i都是为0,用static修饰每次进来都是在上次的值上递增,不用static修饰就会发现六个按钮重叠了。
下面看实现效果
后记
这个纯属娱乐,写着玩的,希望大家喜欢~~~