问题
Im new to swift and learning swift 3
Im trying to pass data from table view controller to XIB file . I have list of fruits in my table view controller. On click of that i would like to display fruit name in a label in new XIB controller. I tried below code but it is not showing me any data in XIB vc..please tell me what am I missing here
My 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)
}
}
Second 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()
}
}
回答1:
The issue is with the following line in your code:
self.present(ShowDetailsXibViewController(), animated: true, completion: nil)
You instantiate a new instance of ShowDetailsXibViewController there and do not use the one you already created with this line:
let detailsVC = ShowDetailsXibViewController(nibName: "ShowDetailsXibViewController", bundle: nil)
If you change the first line to the following, it should work:
self.present(detailsVC, animated: true, completion: nil)
回答2:
The problem is this line:
self.present(ShowDetailsXibViewController(), animated: true, completion: nil)
Here you are creating another ShowDetailsXibViewController
, which is presented. Instead to present the previously created controller, you should write:
self.present(detailsVC, animated: true, completion: nil)
来源:https://stackoverflow.com/questions/42881524/pass-data-from-tableviewcontroller-to-xib-file-without-segues-swift-3