我要做的是:
让每个视图控制器上的所有内容在您的代码中都有一个出口。当您关闭一个 VC 时,将所有这些东西设置为 alpha 为 0。然后推送新的 VC,所有项目都以 0 的 alpha 开头并将它们动画回 1。如果您调用关闭并推送VC 没有动画,则背景图像不会改变,并且会出现上一屏淡出,新一屏淡入,同时保持一致的背景。
这就是你要找的吗?
这是一个更具体的例子:
假设我们有 2 个视图控制器,VC1 和 VC2。 VC1 在框架的中心有一个大按钮(button1),按下它会弹出 VC2。 VC2 只有一个后退按钮(button2),它会将我们返回到 VC1。
我们从 Interface Builder 开始,在这里我们将视图的背景图像设置为 VC1 和 VC2 中的相同图像。然后我们为每个 VC 添加一个按钮,并将它们连接到标题中的适当插座,并在我们的 .m 文件中综合属性。在界面生成器中,将每个按钮的 alpha 设置为零。它会消失,但它仍然存在,只是不可见。
我们还为用户按下每个按钮创建了一个方法,我将在 VC1 中调用 firstButton,在 VC2 中调用 backButton。将它们连接到 button1 和 button2。
除非我们以其他方式对其进行编码,否则我们的按钮是不可见的。因此,当应用程序加载并在屏幕上看到 VC1 时,我们需要将按钮的不透明度重新设置为动画,如下所示。如果您不熟悉动画语法,请不要担心,这很容易。
- (void) viewDidAppear:(BOOL)animated {
// Animations
[UIView animateWithDuration:0.2 // How long the animation takes
delay:0 // Any once we hit this line of code before the animation takes place
options:UIViewAnimationCurveEaseInOut // Play around with this one to see what style of animation you want
animations:^{ // This is where we actually say what we want to animate. Make sure you use block syntax like I have here.
self.button1.alpha = 1;
}
completion:^ (BOOL finished){} // If you want to do something else after the animations are complete you can call that here.
];
}
就是这样!请注意,我是在 viewDidAppear 方法中执行此操作,而不是在 viewDidLoad 或 viewWillAppear 中执行此操作,因为它们发生在屏幕上显示任何内容之前,并且此时没有动画是可能的。
当用户点击 VC1 中的按钮时,我们需要将不透明度设置回零,然后将 VC2 压入堆栈。我们这样做几乎与上一个动画完全相同,但这次我们需要在完成块中更改为 VC2。如果我们使用动画:NO 调用来执行此操作,那么我们不会看到第一个视图滑出。由于背景图片是一样的,看起来我们还是在同一个VC中。
- (void) firstButton {
VC2 *secondVC = [[VC2 alloc] initWithNibName:@"VC2"];
[UIView animateWithDuration:0.2
delay:0
options:UIViewAnimationCurveEaseInOut
animations:^{
self.button1.alpha = 0;
}
completion:^ (BOOL finished){ // Presenting the instance of VC2
[self.navigationController pushViewController:secondVC animated:NO];
}
];
}
现在我们已经完成了 VC1 的所有动画。我们需要将淡入效果复制到VC2的viewDidAppear方法中(我不再复制出来但字面上是一样的),代码是backButton方法,和firstButton方法几乎一模一样,除了我们弹出视图控制器而不是推送一个新的:
- (void) backButton {
[UIView animateWithDuration:0.2
delay:0
options:UIViewAnimationCurveEaseInOut
animations:^{
self.button2.alpha = 0;
}
completion:^ (BOOL finished){ // Removing the instance of VC2
[self.navigationController popViewControllerAnimated:NO];
}
];
}
这样就清楚了吗?