当前位置:  开发笔记 > 编程语言 > 正文

使用pushViewController传递数据?

如何解决《使用pushViewController传递数据?》经验,为你挑选了2个好方法。

使用此代码,我可以"segue"到我的视图控制器的同一个实例

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "DetailVC")
    self.navigationController?.pushViewController(vc, animated: true)


}

但是,如何传递数据?我只知道如何使用segue选项传递数据.当我用这个运行代码时,我得到nil错误,因为新的实例化视图控制器无法读取数据.



1> Anbu.Karthik..:

例如我在这里添加,有关详细说明,您可以从此处获取教程

class SecondViewController: UIViewController {

var myStringValue:String?

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    // We will simply print out the value here
    print("The value of myStringValue is: \(myStringValue!)")
}

并将字符串发送为

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "DetailVC") as! SecondViewController
      vc.myStringValue = "yourvalue"

    self.navigationController?.pushViewController(vc, animated: true)


}



2> Fogmeister..:

首先.这不是一个segue.这只是将另一个视图推向堆栈.并且(如Ashley Mills所说)这与您当前所处的实例不同.这是一个视图控制器的新实例.

但您需要做的就是填充数据.你已经在这里安装了控制器......

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    // you need to cast this next line to the type of VC.
    let vc = storyboard.instantiateViewController(withIdentifier: "DetailVC") as! DetailVC // or whatever it is
    // vc is the controller. Just put the properties in it.
    vc.thePropertyYouWantToSet = theValue

    self.navigationController?.pushViewController(vc, animated: true)
}

推荐阅读
贴进你的心聆听你的世界
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有