这里梳理一下在一个ParentViewController上添加两个SubViewControoler,一个是first一个是second
使用first和second之间转场方法transitionFromViewController调用的一系列方法的顺序
首ParentViewController的代码:
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
|
-
(
void
)
viewDidLoad
{
//first和second这两个子ViewController上面的按钮会发送通知给Parent进行转场
[
[
NSNotificationCenterdefaultCenter
]
addObserver
:
selfselector
:
@
selector
(
dealWithFirstClick
)
name
:
@
"firstClick"
object
:
nil
]
;
[
[
NSNotificationCenterdefaultCenter
]
addObserver
:
selfselector
:
@
selector
(
dealWithSecondClick
)
name
:
@
"secondClick"
object
:
nil
]
;
[
superviewDidLoad
]
;
//生俩儿子
first
=
[
[
FirstViewControlleralloc
]
initWithNibName
:
@
"FirstViewController"
bundle
:
nil
]
;
second
=
[
[
SecondViewControlleralloc
]
initWithNibName
:
@
"SecondViewController"
bundle
:
nil
]
;
//启动后先添加first,大儿子
[
self
addChildViewController
:
first
]
;
[
self
.
view
addSubview
:
first
.
view
]
;
// Do any additional setup after loading the view, typically from a nib.
}
|
然后是重点了,FirstViewController先加载视图,上面有一个按钮,点击了后会跳转到二儿子SecondViewController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
-
(
void
)
dealWithFirstClick
{
//调用addChildViewController之前会自动调用second的willMoveToParentViewController
[
self
addChildViewController
:
second
]
;
[
self
transitionFromViewController
:
firsttoViewController
:
secondduration
:
0.5options
:
UIViewAnimationOptionTransitionFlipFromTopanimations
:
nilcompletion
:
^
(
BOOL
finished
)
{
//addChildViewController之后手动添加的didMoveToParentViewController
[
second
didMoveToParentViewController
:
self
]
;
//删除之前first之前手动添加的willMoveToParentViewController
[
first
willMoveToParentViewController
:
nil
]
;
//调用removeFromParentViewController之后会自动调用first的didMoveToParentViewController
[
first
removeFromParentViewController
]
;
}
]
;
}
|
上面的代码体会一下,addChild和removeFromParent这两件事,这两个核心方法会连带着两个子ViewController分别执行willMove和didMove,也就是一共四个方法,顺序如同我上面注释所说,有两个是自动实现的,有两个是我手动添加的,这个顺序需要体会一下,容易晕,当然不调用didMove和willMove也没问题,我就是写在这里记录下顺序。同理second上面的按钮点击了回到first代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
-
(
void
)
dealWithSecondClick
{
[
self
addChildViewController
:
first
]
;
[
self
transitionFromViewController
:
secondtoViewController
:
firstduration
:
0.5options
:
UIViewAnimationOptionTransitionFlipFromRightanimations
:
nilcompletion
:
^
(
BOOL
finished
)
{
[
first
didMoveToParentViewController
:
self
]
;
[
second
willMoveToParentViewController
:
nil
]
;
[
second
removeFromParentViewController
]
;
}
]
;
}
|
总结:从first到second的dealWithFirstClick方法执行顺序
1.willMoveToParentViewController //first 执行 (AUTO)
2.addChildViewController //Parent执行(MANUAL)
3.didMoveToParentViewController //first 执行(MANUAL)
4.willMoveToParentViewController //second执行(MANUAL)
5.removeFromParentViewController //Parent执行(MANUAL)
6.didMoveToParentViewController //Second执行 (AUTO)
肯定是会晕的,但是细心观察一下就是这么个执行顺序