ios 在没有导航控制器 Swift 的情况下以编程方式更改视图控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29132511/
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-08-31 05:15:20  来源:igfitidea点击:

Programmatically changing View Controllers without Navigation Controller Swift

iosxcodeswiftuiviewcontrollerxcode6

提问by samando

I want to switch to a new view controller when I press a button without using a navigation controller and I can't seem to be able to do this. I have looked everywhere for an answer but everything that I have found is either in objective-c, using a navigation controller, or not working at all.

我想在不使用导航控制器的情况下按下按钮时切换到新的视图控制器,但我似乎无法做到这一点。我到处寻找答案,但我发现的所有内容要么在objective-c 中,使用导航控制器,要么根本不工作。

func gunsoutButtonPressed(sender:UIButton!) {
    print("yay\t")
    //let encounterVC:AnyObject! = self.storyboard?.instantiateViewControllerWithIdentifier("ecounterViewController")
    //self.showViewController(encounterVC as UIViewController, sender: encounterVC)
    let encounterViewController = self.storyboard.instantiateViewControllerWithIdentifier("encounterViewController") as encounterViewController
    self.pushViewController(encounterViewController, animated: true)
}

回答by LinusGeffarth

You have to connect the two ViewControllers you would like to use. Then name the segue however you want and then use the following code to trigger the segue (inside an IBAction or something). It is not completely programmatically but you can trigger them programmatically, which should be enough.

您必须连接要使用的两个 ViewController。然后根据需要命名转场,然后使用以下代码触发转场(在 IBAction 或其他内容中)。它不是完全以编程方式,但您可以以编程方式触发它们,这应该足够了。

performSegueWithIdentifier("mySegue", sender: nil)

Check out this videofor support.

查看此视频以获取支持。

Hope this helps :)

希望这可以帮助 :)

回答by Matt Cooper

You cannot use a push segue without a UINavigationController. You could achieve this with a modal segue, such as this:

没有UINavigationController. 您可以使用模态转场来实现这一点,例如:

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

回答by samando

Segue

赛格

So you use the Segue ID to make sure you segue correctly.

因此,您使用 Segue ID 来确保您正确进行了转场。

No Segue

没有转场

I would suggest doing this instead though:

不过,我建议这样做:

let vc = ViewControllerToSegueTo()
self.presentViewController(vc, animated: true, completion: nil)

It is slightly better if you do not want to use the storyboard.

如果您不想使用故事板,那会稍微好一些。