ios - 使用 pushViewController 传递数据?

标签 ios swift uiviewcontroller segue

使用这段代码,我能够“继续”到我的 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/

相关文章:

android - Google翻译手机应用程序是否使用Tesseract在本地进行OCR?

ios - 带有小页面的 UIPageViewController

ios - UIAutomation 和应用程序之间的通信

ios - 如何按天查询健康包的总事件分钟数?

ios - 如何快速修复 HTTPBODY 的这些参数?

swift - Tableview 原型(prototype)单元高于其他单元

ios - 在上面添加一个 UIView,甚至是导航栏

iOS:如何在弹出 UIViewController 的子 UIViewController 后将其返回 "Refresh"?

ios - MSMessageLayout 在 iMessage 应用程序中没有成员标题

objective-c - UIViewController 子类无法分配实例变量