Swift presentViewController

 手机用户2502937333 发布于 2023-01-11 10:32

我以编程方式在iOS Swift项目中拥有多个View Controller.我没有故事板,如果可能的话,我想避免使用它们.有没有办法切换到另一个viewcontroller.swift文件(我们将调用它view2.swift)并让它成为按钮调用的函数的一部分?
我尝试过以下方法:

let storyboard: UIStoryboard = UIStoryboard(name: "myTabBarName", bundle: nil)
let vc: UIViewController = storyboard.instantiateViewControllerWithIdentifier("myVCID") as UIViewController
self.presentViewController(vc, animated: true, completion: nil)

上面的工作与故事板,但我希望另一个view2.swift被称为.可以这样做吗?

6 个回答
  • 对于那些获得空白/黑屏的人来说,这段代码对我有用.

        let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
        self.present(vc, animated: true, completion: nil)
    

    要为VC设置"标识符",只需转到故事板中VC的身份检查器.将"故事板ID"设置为您想要的标识符.请查看下面的图片以供参考.

    2023-01-11 10:32 回答
  • 试试这个:

    let vc = ViewController() //change this to your class name
    self.presentViewController(vc, animated: true, completion: nil)
    

    使用Swift3:

    self.present(vc, animated: true, completion: nil)
    

    2023-01-11 10:33 回答
  • 对我来说,我在两个独立的导航控制器中有两个视图.我不得不使用上面的组合.

    var vc = self.storyboard?.instantiateViewControllerWithIdentifier("WelcomeViewController") as! WelcomeViewController
        var navigationController = UINavigationController(rootViewController: vc)
        self.presentViewController(navigationController, animated: true, completion: nil)
    

    Swift 3.x

            let secondVC = self.storyboard?.instantiateViewController(withIdentifier: "VC-ID" as! yourViewController
            let navigationVC = UINavigationController(rootViewController: secondVC)
            self.present(navigationVC, animated: true, completion: nil)
    

    2023-01-11 10:33 回答
  • Swift 3和Swift 4

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "idMyViewControllerName") as! MyViewControllerName
    self.present(vc, animated: true, completion: nil)
    

    2023-01-11 10:33 回答
  • 供参考,因为这个问题是谷歌的第一个结果.

    突破Swift 3的变化:

    该方法presentViewController被该方法取代present.

    您可以像旧的一样使用它:

    self.present(viewControllerToPresent, animated: true, completion: nil)
    

    打开相机的示例:

    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.camera
    imagePicker.allowsEditing = false
    self.present(imagePicker, animated: true, completion: nil)
    

    2023-01-11 10:35 回答
  • 使用Swift 2.1+

     let vc = self.storyboard?.instantiateViewControllerWithIdentifier("settingsVC") as! SettingsViewController
     self.presentViewController(vc, animated: true, completion: nil)
    

    在此输入图像描述

    2023-01-11 10:35 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有