【发布时间】:2017-05-14 22:33:37
【问题描述】:
我想将两个不同的数据从两个不同的视图控制器(Table1VC - Table2VC)传递到一个扩展(MainVC)..
我做到了,它的工作..但问题是:
当我传递第一个数据时,这里没有问题 但问题是当我传递第二个数据时,第一个数据消失了!!
这是我到目前为止所做的:
表1VC:
import UIKit
class Table1ViewController: UIViewController , UITableViewDelegate , UITableViewDataSource{
@IBOutlet weak var tableview: UITableView!
var city = ["data1" , "data2" , "Data3"]
var passit = ""
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
self.navigationController?.navigationBar.tintColor = UIColor.orange
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return city.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = city[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
passit = city[indexPath.row]
performSegue(withIdentifier: "showtable1", sender: city[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
let passData1 = segue.destination as! MainVC
passData1.passcity1 = passit
}
}
Table2VC
import UIKit
class passVC: UIViewController , UITableViewDelegate , UITableViewDataSource{
@IBOutlet weak var tableView: UITableView!
var city2 = ["data1" , "data2" , "Data3"]
var passit = ""
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.navigationController?.navigationBar.tintColor = UIColor.orange
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return city2.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = city2[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
passit = city2[indexPath.row]
performSegue(withIdentifier: "showtable2", sender: city2[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
let passData2 = segue.destination as! MainVC
passData2.passcity2 = passit
}
}
主VC
import UIKit
class MainVC: UIViewController {
@IBOutlet weak var passText1: UITextField!
@IBOutlet weak var passText2: UITextField!
var passcity1 = ""
var passcity2 = ""
override func viewDidLoad() {
super .viewDidLoad()
passText1.text = passcity1
passText2.text = passcity2
}
}
传递的数据将在 MainVC 的文本字段中
【问题讨论】:
-
你不能从两个不同的视图控制器中切换到同一个 MainVC 实例;每个 segue 都会创建一个新实例。如果你的表视图用于选择一个你想要传递 back 到 mainvc 的值,那么你应该阅读 unwind segues。
标签: ios swift uitableview segue