将数据从 TableViewController 传递到 XIB 文件而无需 Segues- Swift 3

Pass Data from TableViewController to XIB file Without Segues- Swift 3

我是 swift 的新手,正在学习 swift 3

我正在尝试将数据从 table 视图控制器传递到 XIB 文件。我的 table 视图控制器中有水果列表。单击它我想在新 XIB 控制器的标签中显示水果名称。我尝试了下面的代码,但它没有显示 XIB 中的任何数据 vc..请告诉我我在这里缺少什么

我的桌子VC:

class FruitsTableViewController: UITableViewController {

    var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry",
                  "Clementine", "Coconut", "Cranberry", "Fig", "Grape", "Grapefruit",
                  "Kiwi fruit", "Lemon", "Lime", "Lychee", "Mandarine", "Mango",
                  "Melon", "Nectarine", "Olive", "Orange", "Papaya", "Peach",
                  "Pear", "Pineapple", "Raspberry", "Strawberry"]

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fruits.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = fruits[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let dataToPass = fruits[indexPath.row]
        let detailsVC = ShowDetailsXibViewController(nibName: "ShowDetailsXibViewController", bundle: nil)
        detailsVC.dataFromVC = dataToPass
        self.present(ShowDetailsXibViewController(), animated: true, completion: nil)

    }

}

第二个VC:

class ShowDetailsXibViewController: UIViewController {

    @IBOutlet weak var lblFruit: UILabel!

    var dataFromVC : String?

    override func viewDidLoad() {
        super.viewDidLoad()

        lblFruit.text = dataFromVC
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

问题出在您的代码中的以下行:

self.present(ShowDetailsXibViewController(), animated: true, completion: nil)

您在那里实例化了一个 ShowDetailsXibViewController 的新实例,但不要使用您已经通过此行创建的实例:

let detailsVC = ShowDetailsXibViewController(nibName: "ShowDetailsXibViewController", bundle: nil)

如果将第一行更改为以下内容,应该可以:

self.present(detailsVC, animated: true, completion: nil)

问题出在这一行:

    self.present(ShowDetailsXibViewController(), animated: true, completion: nil)

这里您正在创建另一个 ShowDetailsXibViewController,它被呈现。为了呈现之前创建的控制器,您应该这样写:

    self.present(detailsVC, animated: true, completion: nil)