Hi I have a parent view controller with a mapView
and a child view controller within it, as a small container view on the bottom, and that container view is normally hidden. When I tap on a marker on the mapView
from the parent view controller, I want to show that container view and change the labels on the child view controller to values I get from a database.
Right now, what I have here is me calling the function from the parent view controller (when the marker is tapped) to change the labels on the child view controller.
in my parent view controller:
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
AddressViewController.ID.selectedID = marker.snippet ?? ""
UIView.transition(with: AddressView, duration: 1, options: .transitionFlipFromBottom, animations: {self.AddressView.isHidden = false}, completion: nil)
let AddressViewController = AddressViewController()
AddressViewController.loadAddressView()
let camera = GMSCameraPosition.camera(withTarget: marker.position, zoom: 16)
mapView.animate(to: camera)
return true
}
in AddressViewController (the child view controller)
func loadAddressView() {
if ID.selectedID == "" {
print("ID did not pass")
return
}
else {
print("function worked")
ref = Database.database().reference().child("Items").child(ID.selectedID)
ref?.observeSingleEvent(of: .value, with: {(snapshot) in
let value = snapshot.value as? NSDictionary
self.ItemNameLabel.text = value?["ItemName"] as? String ?? ""
self.addressLabel.text = value?["AddressDisplay"] as? String ?? ""
})
}
}
What is happening is that when I run it and press the marker, it crashes, and it tells me that ItemNameLabel
is "unexpectedly found nil while unwrapping an optional value." However, I could tell the function still was called because "function worked" (above) was still printed, only the label was found nil. So I tried things such as using a delegate and protocol to call the function, which, while it didn't crash, the delegate was never called for some reason (I might of been doing it wrong- if that is how to solve to problem, I would love it if someone please explain how to do it in my case). I also tried setting my label to the database data in the viewDidLoad of the child view controller, and calling the child view controller's loadView() from the parent view controller, and that didn't crash, but didn't change the label either.
Anyone have an idea on how to fix this? Thanks in advance.
question from:
https://stackoverflow.com/questions/65938673/calling-function-from-child-view-controller-not-working 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…