将数据从TableViewController传递到XIB文件没有Segues Swift 3
我新来快速学习3
我试图从表视图控制器传递数据到XIB文件。 我有我的表视图控制器中的水果列表。 点击,我想在新的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的新实例,而不要使用你已经创build的这一行:
let detailsVC = ShowDetailsXibViewController(nibName: "ShowDetailsXibViewController", bundle: nil)
如果您将第一行更改为以下内容,则应该起作用:
self.present(detailsVC, animated: true, completion: nil)
问题是这一行:
self.present(ShowDetailsXibViewController(), animated: true, completion: nil)
在这里你正在创build另一个ShowDetailsXibViewController
,这是呈现。 而不是介绍以前创build的控制器,你应该写:
self.present(detailsVC, animated: true, completion: nil)