如何从子视图导航到mainviewcontroller [英] How can i navigate to mainviewcontroller from subview

查看:110
本文介绍了如何从子视图导航到mainviewcontroller的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用swift,我创建了一个子视图,上面有一个按钮,我想使用该按钮将我带到我的mainviewcontroller。

I have just started working with swift, i have created a subview which has a button on it, i would like to use that button to take me to my mainviewcontroller.

我对不同的按钮使用了相同的功能,但是在同一个文件中有一个功能允许该按钮工作,代码在下面

i have used same functionality for a different button however having a function in same file allows that button to work the code is below

var playAgainButton = UIButton(frame: CGRectMake(0, 150, 320, 40))
            playAgainButton.setTitle("Play Again", forState: UIControlState.Normal)
            playAgainButton.addTarget(self, action: Selector("startGame"), forControlEvents: UIControlEvents.TouchUpInside)
            playAgainButton.backgroundColor = UIColor.redColor()
            gameOver.addSubview(playAgainButton)

是否可以使用类似的代码导航到不同的viewcontroller?

is it possible to use similar code to navigate to a different viewcontroller?

谢谢

推荐答案

您使用的是故事板,还是全部都是代码?如果它在代码中,请创建一个方法,如

Are you using storyboards, or is this all in code? If it's in code, create a method like

func goToMainVC() {
    if let navController = self.navigationController {
        navController.popToRootViewControllerAnimated(true)
    }
}

和将按钮的目标设置为调用它的选择器。

and set the button's target to a selector that calls it.

如果您使用的是故事板,则有三种选择:

If you're using storyboards, you have three options:


  1. 按住ctrl +将连接从按钮拖回主视图控制器(简单但形状不好,因为它只是将主VC推回导航控制器);

  2. 在上面的 fun goToMainVC()方法之前添加 @IBAction ,然后按ctrl +拖动连接你的按钮到它所包含的视图控制器,然后选择那个插座方法(大多数人都这样做);或

  3. 最好的选择是使用展开segue,如此处

  1. ctrl+drag a connection from your button back to the main view controller (easy, but bad form because it just pushes the main VC back onto the nav controller);
  2. Add @IBAction before the fun goToMainVC() method above, then ctrl+drag a connection from your button to the view controller in which it's contained, and then select that outlet method (this is how most people would do it); or
  3. The best option is to use an unwind segue, as described here.

这篇关于如何从子视图导航到mainviewcontroller的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆