xcode 如何在 Swift 中加载初始视图控制器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26656696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:03:13  来源:igfitidea点击:

How to load initial view controller in Swift?

iosiphonexcodeswift

提问by natuslaedo

I am developing an application for a username-passwordbased system. My initial view controller is named LoginPageViewController. If the user logs in successfully, a navigation controller named MyNavigationControlleris loaded. All view controllers except LoginPageViewControllerare accessed via a side-menu I found here: Side Menu Libraryby the help of MyNavigationController.

我正在为基于用户名密码的系统开发应用程序。我的初始视图控制器名为LoginPageViewController. 如果用户登录成功,MyNavigationController则会加载名为的导航控制器。除了LoginPageViewController通过我在此处找到的侧菜单访问之外的所有视图控制器:Side Menu Libraryby the help of MyNavigationController.

View settings of my side menu are described in MyMenuTableViewControllerand if any of table items is selected, relevant view controller is loaded from MyMenuTableViewController. The problem is, I have also added "Logout" item to my side menu (or menu table, whatever you call) and if this item is selected, it makes an HTTP POSTrequest to server to log out and should load the LoginPageViewControllerwhich is my initial view controller (which is not embedded in MyNavigationControlelr).

我的侧边菜单的视图设置在 中描述MyMenuTableViewController,如果选择了任何表项,则从 加载相关的视图控制器MyMenuTableViewController。问题是,我还在我的侧菜单(或菜单表,无论您调用什么)中添加了“注销”项目,如果选择了该项目,它会向服务器发出HTTP POST请求以注销,并且应该加载LoginPageViewController我的初始视图控制器(未嵌入到 中MyNavigationControlelr)。

The problem is, although the logout request is handled successfully, I have been encountering problems while loading my initial view controller (LoginPageViewController).

问题是,尽管注销请求已成功处理,但我在加载初始视图控制器 ( LoginPageViewController) 时遇到了问题。

When I try this when Logout is selected:

当我在选择注销时尝试此操作时:

self.presentViewController(destViewController, animated: true, completion: nil)

LoginPageViewController is being loaded but I get an message like:2014-10-30 16:59:26.038 iOpsGenie[2973:66509] Presenting view controllers on detached view controllers is discouraged <iOpsGenie.MyMenuTableViewController: 0x7f85e8fc3f10>. and if I click any where on Login Page, my view disappears and only a white screen is left.

LoginPageViewController 正在加载,但我收到如下消息:2014-10-30 16:59:26.038 iOpsGenie[2973:66509] Presenting view controllers on detached view controllers is discouraged <iOpsGenie.MyMenuTableViewController: 0x7f85e8fc3f10>. 如果我单击登录页面上的任何位置,我的视图就会消失,只剩下一个白屏。

Then I tried implementing a method

然后我尝试实现一个方法

 func resetAppToFirstController() {
     self.window?.rootViewController = LoginPageViewController(nibName: nil, bundle: nil)
     }

in AppDelegate.swiftand call it when Logout item is being selected:

AppDelegate.swift 中并在选择注销项时调用它:

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.resetAppToFirstController()

Then I got an error in second line of viewDidLoad function of LoginPageViewController like:

然后我在 LoginPageViewController 的 viewDidLoad 函数的第二行出现错误,例如:

fatal error: unexpectedly found nil while unwrapping an Optional value

I know it became a very long question. I may be counted as a newbie on Swift and iOS programming and I tried to state the problem to prevent irrelevant responses. I really wonder what I am missing.

我知道这变成了一个很长的问题。我可能被认为是 Swift 和 iOS 编程的新手,我试图说明问题以防止不相关的响应。我真的想知道我错过了什么。

Best regards

此致

回答by natuslaedo

I solved the problem by changing resetAppToFirstController method to:

我通过将 resetAppToFirstController 方法更改为:

self.window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(PageNames.LOGIN_PAGE) as LoginPageViewController

and firing the following code when Logout is clicked:

并在单击注销时触发以下代码:

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.resetAppToFirstController()

However, I have no idea why this is worked. Any little explanation would be great.

但是,我不知道为什么这是有效的。任何小小的解释都会很棒。

回答by Nischal Hada

In swift we can change the root view controller and in that case all other view controllers will be deallocated and they will no longer be in the hierarchy.

在 swift 中,我们可以更改根视图控制器,在这种情况下,所有其他视图控制器将被释放,它们将不再位于层次结构中。

To load initial view controller or to change root view controller or to make logout action in swift

加载初始视图控制器或更改根视图控制器或快速进行注销操作

let storyboard = UIStoryboard(name: "StartingPage", bundle: NSBundle.mainBundle())      
let loginView: SignInVC = storyboard.instantiateViewControllerWithIdentifier("SignInVC") as! SignInVC
UIApplication.sharedApplication().keyWindow?.rootViewController = loginView

回答by Felipe Ferri

Please allow me to suggest a better way to do what you want, ok? I had a similar problem in another question I posted; please look at the accepted answer at this question.

请允许我提出一个更好的方法来做你想做的事,好吗?我在发布的另一个问题中遇到了类似的问题;请查看此问题的已接受答案。

Pay attention to the storyboard on the answer. It has a hierarchy of view controllers which allow start from a Login Controller, navigate through several controllers and perform a Logout from a menu.

注意答案上的故事板。它具有视图控制器的层次结构,允许从登录控制器启动,浏览多个控制器并从菜单执行注销。

In order to implement this, follow these steps.

为了实现这一点,请按照以下步骤操作。

  1. Make your initial view controller a navigation controller, with root view being your Login controller.

  2. Make your login controller Push Segue the Menu controller.

  3. Perform an "unwind segue" from the Logout button of the menu view to the login view.

  1. 使您的初始视图控制器成为导航控制器,根视图是您的登录控制器。

  2. 使您的登录控制器 Push Segue 成为 Menu 控制器。

  3. 从菜单视图的 Logout 按钮到登录视图执行“unwind segue”。

An unwind segue will remove all the views from a navigation stack until it reaches a view you specify.

unwind segue 将从导航堆栈中删除所有视图,直到它到达您指定的视图。

Unwind segues are really easy to use and can solve a lot of problems!

Unwind segues真的好用,可以解决很多问题!

Add the following method definition on your login view controller:

在您的登录视图控制器上添加以下方法定义:

@IBAction func unwindToLoginScreen(segue:UIStoryboardSegue) {
}

Then, on storyboard editor, select any view controller from which you want to be able to unwind. On the top of the view controller you have three icons.

然后,在故事板编辑器上,选择您希望能够从中放松的任何视图控制器。在视图控制器的顶部,您有三个图标。

enter image description here

enter image description here

The first represents the view controller; the second is the First Responder; the third is an Exit door.

第一个代表视图控制器;第二个是第一响应者;第三个是出口门。

Perform a "Control+Drag" from the first to the third icon; a drop down menu will appear referencing all the "unwind segue" declarations you made on your code. Our unwindToLoginScreen segue should appear here. Select it.

从第一个图标到第三个图标执行“Control+Drag”;将出现一个下拉菜单,引用您在代码中所做的所有“unwind segue”声明。我们的 unwindToLoginScreen segue 应该出现在这里。选择它。

enter image description here

enter image description here

On the Document Outline at the left bar of the storyboard editor will appear an Unwind Segue on the hierarchy of the view controller. Select it and change its identifier to something like "Login".

在故事板编辑器左侧栏的文档大纲上,将在视图控制器的层次结构上显示一个 Unwind Segue。选择它并将其标识符更改为“登录”之类的内容。

Now, you can call performSegueWithIdentifier("Login") if you want to go back to the login screen.

现在,如果您想返回登录屏幕,可以调用 performSegueWithIdentifier("Login")。

The advantages of using unwind segues is that you know for sure that all the views in the stack are being deallocated, that you can call preparation code in the prepareForSegue method in the origin view controller, some code in your destination view controller just before finishing the segue; and that connections between different view controllers are visible on the storyboard editor (not so evident as in regular segues, though).

使用 unwind segues 的好处是你可以确定堆栈中的所有视图都被释放了,你可以在源视图控制器的 prepareForSegue 方法中调用准备代码,在完成之前你的目标视图控制器中的一些代码转场;并且不同视图控制器之间的连接在故事板编辑器上是可见的(虽然不像在常规 segue 中那么明显)。

回答by Deep Krishna sharma

Swift 4

斯威夫特 4

Syntax is changed in swift4 : If you want to go to "FirstViewController" in StoryBoard "Main" try below code

swift4 中的语法已更改:如果您想转到 StoryBoard“Main”中的“FirstViewController”,请尝试以下代码

let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)

让 storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)

let firstviewcontroller = storyboard.instantiateViewController(withIdentifier: "FirstViewController") as! FirstViewController

让 firstviewcontroller = storyboard.instantiateViewController(withIdentifier: "FirstViewController") 作为!第一视图控制器

UIApplication.shared.keyWindow?.rootViewController = firstviewcontroller

UIApplication.shared.keyWindow?.rootViewController = firstviewcontroller