如何在没有 segue 的情况下将数据从 UITableView 传递到 UIViewController

How to pass data from UITableView to UIViewController without segue

我需要将 UITableView 中行的标题传递给我的 ViewController。我在情节提要中没有 VC (我是通过代码创建的)。所以我不能使用segue。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

   let cell = tableView.cellForRow(at: indexPath) as! UITableViewCell


    cell.textLabel?.textColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
    cell.textLabel?.tintColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)

        var titleOfFood = String()
        if searching == true {
           titleOfFood = searchedFoods[indexPath.row].title
            cell.textLabel?.textColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
             print(titleOfFood)
        } else {
            titleOfFood = foods[indexPath.row].title
            cell.textLabel?.textColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
             print(titleOfFood)
        }

    let controller = EatenFoodViewController()
    let transitionDelegate = SPStorkTransitioningDelegate()
    controller.transitioningDelegate = transitionDelegate
    controller.modalPresentationStyle = .custom
    //controller.delegate = self
    transitionDelegate.customHeight = 620
    transitionDelegate.showIndicator = false
    self.present(controller, animated: true, completion: nil)
}

我需要将 titleOfFood 传递给 EatenFoodViewController

您不需要 segue 将数据发送到目的地 vc ,您可以简单地做

controller.titleOfFood = arr[indexPath.row].title // assuming you have an array of models 

controller.titleOfFood = cell.textLabel!.text!

class EatenFoodViewController:UIViewController {
   var titleOfFood = ""
}