我是 Swift 新手,正在学习 Swift 3
我正在尝试将数据从 TableView Controller 传递到 XIB 文件。我的 TableView Controller 中有水果列表。单击该按钮后,我想在新 XIB Controller 的标签中显示水果名称。我尝试了下面的代码,但它没有向我显示 XIB vc 中的任何数据。请告诉我我在这里缺少什么
我的TableVC:
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)
}
}
第二个风险投资:
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)
关于ios - 将数据从 TableViewController 传递到 XIB 文件而不使用 Segues-Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42881524/