使用这段代码,我能够“继续”到我的 View Controller 的同一个实例
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 错误,因为新的实例化 View Controller 无法读取数据。
最佳答案
例如我在这里添加,详细说明可以从here获取教程
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)
}
关于ios - 使用 pushViewController 传递数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41804194/