Search code examples
iosswiftuiviewcontrollergoogle-maps-sdk-ios

Access to ViewController outlet from TableViewController loaded at same time


I was reading the thread: IBOutlet of another view controller is nil

I have a problem very similar to that.

RequestViewController

class DenunciasResueltasViewController: UIViewController {

    @IBOutlet var mapView: GMSMapView!
    var solicitudes = [SolicitudesModel]()
    var tempMap: GMSMapView!

        override func viewDidLoad() {
            super.viewDidLoad()

            let camera = GMSCameraPosition.camera(withLatitude: 3.4824182, longitude: -8.1776567, zoom: 15)
            self.mapView.camera = camera
    }

func recenterMap(latitude:Float!, longitude:Float!) -> Void {

        let coordinates = CLLocationCoordinate2DMake(CLLocationDegrees(latitude), CLLocationDegrees(longitude))
        mapView = tempMap
        self.mapView.animate(toLocation: coordinates)
    }

RequestTableViewController

class RequestTableViewController: UITableViewController {
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

//Some code to fill the table


        let viewController = self.storyboard?.instantiateViewController(withIdentifier: "RequestVC") as! RequestViewController
        viewController.recenterMap(latitude: solicitudes[indexPath.row].getLatitude(), longitude: solicitudes[indexPath.row].getLongitude() )

        return cell
    }
}

Both components are initialized at same time in runtime, I mean, both are part of the same View.

And when the users click in a 'row' I wanna update the mapView

for that resason, I'm using the method 'RecenterMap'

But, the variable 'self.mapView' is always 'nil'. How I can update this value?


Solution

  • You should use the delegate method didSelectRowAtIndexPath to do the recentering, because this is called when the user tapps on a cell. It could be that the Outlets of the first viewcontroller haven't yet been set when the second starts to fill its cells.