0

I want to pass the selected coordinates from a view controller called ResultsVC to a view controller called SearchMapViewController. SearchMapViewController should take the coordinate and pin on the map. I know I have to delegate the SearchMapViewController to ResultsVC but I don't know how to do that. I instantiate an object (let resultsVC = ResultsVC() ) then inside viewDidLoad(), I say resultsVC.delegate = self in the class of SearchMapViewController but it doesn't work because I created a brand new view controller which does not have the chosen coordinates. How I am suppose to refer the initial ResultsVC? Please help.

protocol ResultsVCDelegate: AnyObject {
func didTapPlace(with coordinates: CLLocationCoordinate2D, address: String)
}

class ResultsVC: UIViewController,UITableViewDelegate,UITableViewDataSource
{
  weak var delegate:ResultsVCDelegate?
            
  let tableView = UITableView()
            
  var locations = [Location]()
            
  override func viewDidLoad() {
  super.viewDidLoad()
  view.addSubview(tableView)
  tableView.backgroundColor = .systemBackground
  tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
  tableView.delegate = self
  tableView.dataSource = self
                               }
            
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
  {
                tableView.deselectRow(at: indexPath, animated: true)
                tableView.isHidden = true
                let selectedCoordinates = locations[indexPath.row].coordinates
                let locationName = locations[indexPath.row].title
                self.delegate?.didTapPlace(with: selectedCoordinates, address: locationName)
   }
}


class SearchMapViewController: UIViewController, ResultsVCDelegate
{
    
    
    let mapView = MKMapView()
    let resultsVC = ResultsVC()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(mapView)
        resultsVC.delegate = self
    }
    
    override func viewDidLayoutSubviews() {
        mapView.frame = CGRect(x:0,y:view.safeAreaInsets.top,width:view.frame.size.width,height: view.frame.size.height)
    }

    func didTapPlace(with coordinates: CLLocationCoordinate2D, address: String) {
        let pin = MKPointAnnotation()
        pin.coordinate = coordinates
        mapView.addAnnotation(pin)
        mapView.setRegion(MKCoordinateRegion(center: coordinates, span: MKCoordinateSpan(latitudeDelta: 0.7, longitudeDelta: 0.7)), animated: true)
    }
}

0 Answers0