[英]Present and dismiss modal view controller
任何人都可以给我示例代码,我可以用它来首先呈现一个模态视图控制器,然后关闭它? 这是我一直在尝试的:
NSLog(@"%@", blue.modalViewController);
[blue presentModalViewController:red animated:YES];
NSLog(@"%@", blue.modalViewController);
[blue dismissModalViewControllerAnimated:YES];
NSLog(@"%@", blue.modalViewController);
这段代码在 viewDidLoad 中(“blue”和“red”都是 UIViewController 的子类)。 我希望我会显示红色视图,然后立即隐藏它,并带有一些动画。 然而,这段代码只显示了模态视图,并没有关闭它。 任何的想法? 第一个日志显示“null”,而其他两个日志显示<RedViewController: 0x3d21bf0>
还有一点是,如果我把这段代码放在 applicationDidFinishLaunching 中:红色视图根本不出现,所有日志都得到“空”
首先,当您将该代码放入 applicationDidFinishLaunching 时,可能会出现从 Interface Builder 实例化的控制器尚未链接到您的应用程序的情况(因此 "red" 和 "blue" 仍然是nil
)。
但是要回答您最初的问题,您做错了什么是您在错误的控制器上调用了dismissModalViewControllerAnimated:
! 应该是这样的:
[blue presentModalViewController:red animated:YES];
[red dismissModalViewControllerAnimated:YES];
通常,“红色”控制器应该决定在某个时候(可能是单击“取消”按钮时)自行解散。 然后“红色”控制器可以调用self
上的方法:
[self dismissModalViewControllerAnimated:YES];
如果它仍然不起作用,则可能与控制器以动画方式呈现的事实有关,因此您可能不允许在呈现控制器后很快关闭它。
为 Swift 3 更新
创建两个视图控制器,每个控制器上都有一个按钮。 对于第二个视图控制器,将类名设置为SecondViewController
,将故事板 ID 设置为secondVC
。
视图控制器.swift
import UIKit
class ViewController: UIViewController {
@IBAction func presentButtonTapped(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myModalViewController = storyboard.instantiateViewController(withIdentifier: "secondVC")
myModalViewController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
myModalViewController.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(myModalViewController, animated: true, completion: nil)
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
@IBAction func dismissButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
来源:
我在 xcode 4.52 中厌倦的最简单方法是创建一个额外的视图并使用 segue 模式连接它们(控制将按钮从一个视图拖动到第二个视图,选择模态)。 然后将按钮拖入第二个视图或您创建的模态视图。 控制并拖动此按钮到头文件并使用操作连接。 这将在您的 controller.m 文件中创建一个 IBaction。 在代码中找到您的按钮操作类型。
[self dismissViewControllerAnimated:YES completion:nil];
presentModalViewController:
MainViewController *mainViewController=[[MainViewController alloc]init];
[self.navigationController presentModalViewController:mainViewController animated:YES];
解雇ModalViewController:
[self dismissModalViewControllerAnimated:YES];
最简单的方法是使用 Storyboard 和 Segue。
只需创建一个从 TabBarController 的 FirstViewController(不是导航控制器)到带有登录 UI 的 LoginViewController 的 Segue,并将其命名为“showLogin”。
创建一个返回 BOOL 的方法来验证用户登录和/或他/她的会话是否有效......最好在 AppDelegate 上。 称之为SessionValid。
在您的 FirstViewController.m 上重写方法 viewDidAppear,如下所示:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if([self isSessionValid]==NO){
[self performSegueWithIdentifier:@"showLogin" sender:self];
}
}
然后,如果用户成功登录,只需关闭或弹出 LoginViewController 以显示您的选项卡。
100% 有效!
希望能帮助到你!
迅速
self.dismissViewControllerAnimated(true, completion: nil)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.