タイマーイベントを遅延実行するサンプルを以下に作成しました。
サンプルでは、タイマーを定義した2秒後にラベルのアニメーションイベントを呼び出しています。
サンプルダウンロード
タイマー定義
1
2
3
4
5
6
7
8
9
10
| //遅延実行のタイマー定義
- (void)setTimeInterval
{
//2秒後にセレクタメソッドを実行する
_completedTimer = [NSTimer scheduledTimerWithTimeInterval:2.0f
target:self
selector:@selector(onCompletedAnimationTimerEvent:)
userInfo:nil
repeats:NO];
}
|
タイマー削除
1
2
3
4
5
| //遅延実行のタイマーイベント
- (void)onCompletedAnimationTimerEvent:(id)sender
{
[_completedTimer invalidate];
}
|
ソースコード
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
| #import "ViewController.h"
@interface ViewController ()
//アニメーションさせるラベル
@property UILabel *animationLabel;
//遅延実行タイマー
@property NSTimer *completedTimer;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//遅延実行のタイマー定義
[self setTimeInterval];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//遅延実行のタイマー定義
- (void)setTimeInterval
{
//2秒後にセレクタメソッドを実行する
_completedTimer = [NSTimer scheduledTimerWithTimeInterval:2.0f
target:self
selector:@selector(onCompletedAnimationTimerEvent:)
userInfo:nil
repeats:NO];
}
//遅延実行のタイマーイベント
- (void)onCompletedAnimationTimerEvent:(id)sender
{
[_completedTimer invalidate];
[self initAnimationLabel];
[self slideInAnimation];
}
//アニメーションさせるラベルを初期化
- (void)initAnimationLabel
{
_animationLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 568, 320, 568)];
_animationLabel.backgroundColor = [UIColor blackColor];
[self.view addSubview:_animationLabel];
}
//スライドインアニメーション
- (void)slideInAnimation
{
//アニメーション開始
[UIView beginAnimations:nil context:NULL];
//アニメーション秒数
[UIView setAnimationDuration:1.0f];
//デリゲート指定
[UIView setAnimationDelegate:self];
//アニメーションの目標値を指定
[_animationLabel setFrame:CGRectMake(0, 0, 320, 568)];
//アニメーション実行
[UIView commitAnimations];
}
@end
|
お薦めの参考書
詳解 Swift 改訂版
Swiftのかなり入り込んだところまで解説しながら、実践コードを多数収録しています。応用本になりますので、入門書を読み終えて中級者から上級者に差し掛かる時に読むことをお勧めします。読み物としてだけではなくリファレンスとしても使用できます。