首页 > 解决方案 > 从另一个类访问@IBOutlet

问题描述

我目前正在制作一个路线跟踪应用程序来快速自学。我有使用被跟踪的路线的基本功能,并且从单个 SessionController 类中绘制了一条折线,但我想将该类拆分为单独的对象。

这就是我遇到问题的地方。我将所有更新位置和绘制折线等的代码放入其自己的名为 MapView.swift 的类中,并将 @IBOutlets 留给按钮、mapView 等。在 SessionController.swift 但现在我无法访问 @IBOutlet让 mapView 允许新的 MapView.swift 类更新当前位置、更新折线等。

当我尝试按 ctrl + 将 mapView @IBOutlet 拖动到 MapView.swift ViewController 时,没有任何反应。

所以,我要问的是如何链接这两个类以允许访问 SessionController 中的 mapView 以使用当前位置进行更新。

我一直在查找协议和委托,但我不太确定如何实现它们,或者即使这是正确的方法。

SessionController 的代码如下所示:

class SessionController: UIViewController 
{

    // Creates an outlet link to the corrosponding interfaces on the storyBoard
    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet weak var startButton: UIButton!
    @IBOutlet weak var stopButton: UIButton!

    var mapScreen: MapView! = nil

    // Had to change from viewOnLoad so that the custom alert class could be utilised.
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidLoad()
        startButton.layer.cornerRadius = startButton.frame.size.height/2
        stopButton.layer.cornerRadius = stopButton.frame.size.height/2

        mapScreen = (storyboard?.instantiateViewController(withIdentifier: "mapScreen") as! MapView)

        // does the initial check whether the location services are enabled
        mapScreen.checkLocationServices()
    }

    // ends the current session, resets buttons, stops updating location and changes to history tab.
    func endSession() {
        stopButton.isHidden = true
        startButton.isHidden = false
        mapScreen.stopUpdatingLocation()
    }

    // action for when the start button is presssed.
    @IBAction func startButtonPressed(_ sender: Any) {
        mapScreen!.startUpdatingLocation()
        startButton.isHidden = true
        stopButton.isHidden = false
    }

    // action for when the stop button is pressed.
    @IBAction func stopButtonPressed(_ sender: Any) {
        presentAlertWithTitle(title: "End Session?", message: "Do you wish to end your session?", options: "Cancel", "Yes") { (option) in
            switch(option) {
            case 0:
                break
            case 1:
                self.endSession()
            default:
                break
            }
        }
    }
}

MapView 的代码如下所示:

    class MapView: UIViewController 
    {

        let locationManager = CLLocationManager()
        var myLocations: [CLLocation] = []
        let regionInMeters: Double = 500
        var mapView: MKMapView!

        //  Checks the users location services are enabled otherwise give them an alert.
        func checkLocationServices() {
            if CLLocationManager.locationServicesEnabled() {
                setupLocationManager()
                checkLocationAuthorisation()
            } else {
                // show an alert instructing on how to enable location services.
                presentAlertWithTitle(title: "Location Services Disabled", message: "Please enable your location services by navigating to Settings/Privacy/Location Services and turning on.", options: "OK") { _ in }
            }
        }

        // Setup the location manager
        func setupLocationManager() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
        }

        // Checks whether the user has authorised location tracking via permissions.
        func checkLocationAuthorisation() {
            switch CLLocationManager.authorizationStatus() {
            case .authorizedWhenInUse:
                centerViewOnUserLocation()
            case .denied:
                // show alert detailing that the user has denied access to the location services.
                presentAlertWithTitle(title: "Access Denied", message: "Request of access has been denied to the location services", options: "OK") { _ in }
            case .notDetermined:
                locationManager.requestWhenInUseAuthorization()
            case .restricted:
                // show an alert instructing that the location services are restricted i.e. child account
                presentAlertWithTitle(title: "Access Restricted", message: "Access has been restricted to the location services", options: "OK") { _ in }
                break
            case .authorizedAlways:
                break
            }
        }

        // Centers the position onto the at the specified height by using the regionInMeters variable
        func centerViewOnUserLocation() {
            if let location = locationManager.location?.coordinate {
                let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
                mapView.setRegion(region, animated: true)
            }
        }

        func updatePolyLine() {
            if (myLocations.count > 1){
                // get my old location
                let sourceIndex = myLocations.count - 1
                // get the new location
                let destinationIndex = myLocations.count - 2

                // get the coordinates for both the old and the new locations
                let sourceIndexCoordinate = myLocations[sourceIndex].coordinate
                let destinationIndexCoordinate = myLocations[destinationIndex].coordinate

                // put these coordinates in to a new array so that we can get a reference to a pointer so that the MKPolyline can make use of it's position in the registry.
                var sourcePlusDestination = [sourceIndexCoordinate, destinationIndexCoordinate]

                // pass the reference of the array pointer into the constructor of MKPolyline so that a line can be drawn between the two points.
                let polyline = MKPolyline(coordinates: &sourcePlusDestination, count: sourcePlusDestination.count)

                // adds and then updates the polyline on the map.
                mapView.addOverlay(polyline)
            }
        }

        func startUpdatingLocation()
        {
            locationManager.startUpdatingLocation()
        }

        func stopUpdatingLocation()
        {
            locationManager.stopUpdatingLocation()
            tabBarController?.selectedIndex = 1

            for overlay in mapView.overlays {
                mapView.removeOverlay(overlay)
            }
        }
    }

// an extension for SessionController that uses delegates to listen for changes in the location and authorisation
extension MapView: CLLocationManagerDelegate 
{

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
    {
        guard let location = locations.last else { return }
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion.init(center: center, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
        mapView.setRegion(region, animated: true)

        myLocations.append(locations[0] as CLLocation)
        updatePolyLine()
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) 
    {
        checkLocationAuthorisation()
    }
}

extension MapView: MKMapViewDelegate 
{

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer 
    {
        if overlay is MKPolyline 
        {
            let polylineRenderer = MKPolylineRenderer(overlay: overlay)
            polylineRenderer.strokeColor = UIColor.blue
            polylineRenderer.lineWidth = 4
            return polylineRenderer
        }
        return MKPolygonRenderer()
    }
}

标签: iosswiftcocoa-touchuiviewcontrolleriboutlet

解决方案


我对您的代码和问题感到有些困惑,但希望这可以引导您走上正确的道路...

你在这里创建你的 mapScreen:

mapScreen = (storyboard?.instantiateViewController(withIdentifier: "mapScreen") as! MapView)

但永远不要mapView像这样设置它的属性:

mapScreen = (storyboard?.instantiateViewController(withIdentifier: "mapScreen") as! MapView)
mapScreen.mapView = mapView

考虑到您已经实现了它,您似乎也想将您的代表设置为MKMapViewmapScreen ( extension MapView: MKMapViewDelegate)

例如

mapScreen = (storyboard?.instantiateViewController(withIdentifier: "mapScreen") as! MapView)
mapScreen.mapView = mapView
mapView.delegate = mapScreen

另外,我认为您需要对MKMapViewinside进行弱引用MapView

我也看不出你是如何呈现的mapScreen,你似乎实例化了它,但实际上并没有呈现它。我认为您的故事板或更多代码的屏幕截图可能会有所帮助。


推荐阅读