Я не могу выполнять функции из ViewController в другом - PullRequest
0 голосов
/ 09 ноября 2019

Может кто-нибудь помочь мне выполнить функции из одного VC в другом VC. Функция из первого VC должна быть выполнена, как только я нажму кнопку во втором VC. Я пытаюсь с помощью функции "viewcontroller (). Function ()", но она не работает должным образом, печать и основные вещи работают, но когда дело доходит до таких вещей, как направление рисования, это не работает.

Функция, которая рисует направления:

func directionToPin() {

    guard let currentPlacemark = currentPlacemark else {
        print("Error, the current Placemark is: \(self.currentPlacemark)")
        return
    }

    let directionRequest = MKDirections.Request()
    let destinationPlacemark = MKPlacemark(placemark: currentPlacemark)

    directionRequest.source = MKMapItem.forCurrentLocation()
    directionRequest.destination = MKMapItem(placemark: destinationPlacemark)
    directionRequest.transportType = .walking

    //calculate route
    let directions = MKDirections(request: directionRequest)
    directions.calculate{ (directionsResponse, error) in

        guard let directionsResponse = directionsResponse else {
            if let error = error {
                print("error getting directions: \(error.localizedDescription)")
            }
            return
         }

        let route = directionsResponse.routes[0]

        if self.drawedDriection == false {
            self.drawedDriection = true

            if self.didSelectAnnotation == true {
                self.mapView.addOverlay(route.polyline, level: .aboveRoads)self.navigationBarController.directionButtonOutlet.setImage(UIImage(named: "navigationBarDirectionButtonRed")?.withRenderingMode(.alwaysOriginal), for: .normal)
                        self.mapView.setRegion(MKCoordinateRegion(routeRect), animated: true)
                    }
                } else {
                    self.drawedDriection = false
                    self.mapView.removeOverlays(self.mapView.overlays)
                    if self.didSelectAnnotation == true {
                        self.navigationBarController.directionButtonOutlet.setImage(UIImage(named: "navigationBarDirectionButtonBlue")?.withRenderingMode(.alwaysOriginal), for: .normal)
                    } else {
                        self.navigationBarController.directionButtonOutlet.setImage(UIImage(named: "navigationBarDirectionButtonGray")?.withRenderingMode(.alwaysOriginal), for: .normal)
                    }
                }
            }
        }

Я вызываю функцию во втором ВК, когда нажимаю кнопку:

@IBAction func directionButton(_ sender: Any) {
    MapViewController().directionToPin()
} 

Когда я запускаю приложение и нажимаю кнопку currentPlacemark равно нулю, если я запускаю ту же функцию через кнопку в моем первом ВК (ВК с функцией directionToPin внутри)

вот мой репо, если вам это нужно: https://github.com/octavi42/xCodeMapsApp

Спасибо!

1 Ответ

2 голосов
/ 09 ноября 2019

Я думаю, что вам нужно использовать Протоколы и делегаты для достижения желаемого.

@IBAction func directionButton(_ sender: Any) {
    MapViewController().directionToPin()
} 

В приведенном выше фрагменте кода вы создаете новый экземпляр MapViewController , который при инициализации сбрасывает currentPlacemark и, следовательно, вы встретили nil .

Я предлагаю создать новый протокол для связи от MapViewController до CardViewController просто так

Добавить их в MapViewController.swift

protocol MapNavigationDelegate: AnyObject {
    func didTapDirectionButton()
}

class MapViewController: UIViewController {
    // .... Some code ....

    override func viewDidLoad() {
        // . .... Some more code .......
        navigationBarController.mapNavigationDelegate = self
    }
}

extension MapViewController: MapNavigationDelegate {
    func didTapDirectionButton() {
        self.directionToPin()
    }
}

Добавьте их в CardViewController.swift

class CardViewController: UIView {
    // .... Some Code ....
    weak var mapNavigationDelegate: MapNavigationDelegate!

    @IBAction func directionButton(_ sender: Any) {
        self.mapNavigationDelegate.didTapDirectionButton()
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...