【问题标题】:How can I pass data from "didSelectRowAt" to another VC without presenting it or a segue?如何在不显示或 segue 的情况下将数据从“didSelectRowAt”传递到另一个 VC?
【发布时间】:2020-05-23 03:14:42
【问题描述】:

我基本上想要的是我想在我的TableViewController 中按下一行,然后获取该行所具有的 text 并将其传递给ViewController,即目前不存在。就像您在 Spotify 应用程序 中单击一首歌曲时,它会在不显示任何内容的情况下播放歌曲,但歌曲的详细信息会显示在迷你播放器中。

有人知道怎么做吗?

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    你可以这样做,但你需要先初始化你的 View Controller 才能访问它的属性,例如:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DestinationVc") as? DestinationVc
        vc?.text = "TextToBePassed"
    }
    

    没有展示它就在那里,但我不明白你为什么不想展示或展示它,但这就是根据你的问题完成的。谢谢:)

    【讨论】:

      【解决方案2】:

      如果您通过XIBprogramatically 创建了用户界面,请遵循以下方法:

      func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      
        let nextVC = NextViewController()
        nextVC.text = model?[indexPath.row].text // If you are using model or if you have stored the data in the array then nextVC.text = yourArray[indexPath.row]["text"]    
        self.navigationController?.pushViewController(nextVC,animated: true)
      
      }
      

      另外,在NextViewController 中,您必须添加文本。像这样:

      class NextViewController: UIViewController {
      
        var text = String()
      
        //MARK:- View Life Cycle
      
        override func viewDidLoad() {
           super.viewDidLoad()
           print(text) //This will print the text passed from previous VC
        }
      }
      

      【讨论】:

        【解决方案3】:
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let vc = NextViewController()
            vc.title = "\(Title)"
            self.navigationController?.pushViewController(vc,animated: true)
        }
        

        使用此方法可以帮助您在不使用 segue 的情况下将数据传递给另一个 Controller。

        【讨论】:

          【解决方案4】:

          假设这是针对 iOS 的,因为问题没有指定。

          UITableViewDelegatetableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 方法中,您可以使用

          let cell = tableView.cellForRow(at: indexPath)?.textLabel?.text // cell: String?
          

          然后,如果您愿意,您可以将其分配给全局变量,或者如果您维护对不存在的视图控制器的引用,您可以给它一个属性来存储此文本并在调用 performSegue(withIdentifier identifier: String, sender: Any?) 之前分配它。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-03-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多