使用此代码,我可以"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错误,因为新的实例化视图控制器无法读取数据.
例如我在这里添加,有关详细说明,您可以从此处获取教程
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) }
首先.这不是一个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) }