我正在尝试使用委托将数据从模式VC传递到父VC。 这是我显示第二个VC的方式:
let vc = UIStoryboard(name: "Stations", bundle: nil).instantiateViewController(withIdentifier: "StationsVC")
let stations = StationsVC()
stations.delegate = self
present(vc, animated: true)
它有一个委托人:
weak var delegate: SelectedStationDelegate?
这很简单:
protocol SelectedStationDelegate: class {
func setSelectedStation(name: String, color: UIColor)
}
当我关闭它时,第二条VC发送数据:
private func sendSelectedStation(for indexPath: IndexPath) {
if let indexPath = self.tableView.indexPathForSelectedRow {
let cell = self.tableView.cellForRow(at: indexPath) as! StationCell
guard let selectedStationName = cell.label.text else { return }
guard let selectedStationColor = cell.circleView.backgroundColor else { return }
dismiss(animated: true) {
self.delegate?.setSelectedStation(name: selectedStationName, color: selectedStationColor)
}
}
}
我认为它可能不会捕获任何信息,但是可以捕获-至少断点是这样。
第一个VC应该接受它并更改标签的文本和视图的颜色:
extension MapVC: SelectedStationDelegate {
func setSelectedStation(name: String, color: UIColor) {
fromLabel.text = name
print(name)
print(fromLabel.text!)
fromCircle.backgroundColor = color
}
}
但是您猜到了,事实并非如此。此功能从不执行。问题是什么?我想这是因为present()和dismiss()的缘故,但是我根本找不到关于没有委托或导航控制器的使用委托的任何信息:(
答案 0 :(得分:2)
您做错了什么是将委托设置为视图控制器的一个实例,并提供另一个实例。
let vc = UIStoryboard(name: "Stations", bundle: nil).instantiateViewController(withIdentifier: "StationsVC") as! StationsVC
vc.delegate = self
present(vc, animated: true)
答案 1 :(得分:1)
let vc = UIStoryboard(name: "Stations", bundle: nil).instantiateViewController(withIdentifier: "StationsVC") //you are creating second vc
let stations = StationsVC() //also creating another second vc, remove this line
stations.delegate = self
present(vc, animated: true)
使用@Sanket Bhavsar答案:)
答案 2 :(得分:1)
您正在创建两个视图控制器实例
let vc = UIStoryboard(name: "Stations", bundle: nil).instantiateViewController(withIdentifier: "StationsVC") //here
let stations = StationsVC() // here
stations.delegate = self
present(vc, animated: true)
第二秒钟,您不会显示stations
您已分配了代理人,但您正在显示的控制器vc
中尚未分配代理人和
如果出示station
控制器,则可能会导致应用程序崩溃,因为不会初始化所有插座(如果已给出)。
因此,如果您使用情节提要和出口,请使用此
guard let vc = UIStoryboard(name: "Stations", bundle: nil).instantiateViewController(withIdentifier: "StationsVC") as? StationsVC else {return}
vc.delegate = self
present(vc, animated: true)
并且如果您仅使用编程来创建视图控制器,则
let stations = StationsVC() // here
stations.delegate = self
present(vc, animated: true)
答案 3 :(得分:1)
output = Dense(3, activation="sigmoid")(dense)
尝试使用以下代码行:
You have created two instances for StationVC class.
let vc = UIStoryboard(name: "Stations", bundle: nil).instantiateViewController(withIdentifier: "StationsVC") // First Instance
let stations = StationsVC() // Second Instance-- remove this line of code