CollectionView单元格内的MapView不显示折线Swift 4

时间:2019-03-20 13:31:12

标签: ios swift uicollectionview mkmapview

我有一个CollectionView,它显示了保存到CoreData中的所有跟踪路线。除了在单元格内的地图上缺少poly line之外,其他所有功能都可以正常工作。我以为是因为我忘记导入CoreLocation并将其委托分配给ViewCOntroller' but it is still not showing up after adding it. In单元格configuration I print the array from fetched object and it prints it correctly. In my main MapViewController i use the same process but here is not working as expected. Can you see what I'm missing out? Here's the code for the ViewController`:

import UIKit
import MapKit
import CoreData
import CoreLocation

class MyRoutesViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var routeCollectionView: UICollectionView!

    @IBOutlet weak var myRoutesButton: UIButton!

    var fetchedResultController: NSFetchedResultsController<Route>!


    override func viewDidLoad() {
        super.viewDidLoad()

        routeCollectionView.dataSource = self
        routeCollectionView.delegate = self

        myRoutesButton.layer.borderWidth = 1
        myRoutesButton.layer.masksToBounds = true
        myRoutesButton.layer.cornerRadius = myRoutesButton.frame.height/4
        myRoutesButton.layer.borderColor = UIColor.white.cgColor
        configureFetchedResultsController()
    }

    func configureFetchedResultsController() {
        let context = AppDelegate.viewContext
        let fetchRequest = NSFetchRequest<Route>(entityName: "Route")
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
        fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        do {
            try fetchedResultController.performFetch()
            print("fetched")
        } catch  {
            fatalError("failed to fetch entities: \(error)")
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        guard let sections = self.fetchedResultController?.sections else {
            fatalError("no sections in fetchedResultController" )
        }
        let sectionInfo = sections[section]
        return sectionInfo.numberOfObjects
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Route Cell", for: indexPath as IndexPath) as! RouteCell
        let route = self.fetchedResultController?.object(at: indexPath)

        cell.titleValueLabel.text = route!.name //RoutesArray.routeArray[indexPath.row].routeName ?? ""
        cell.distanceValueLabel.text = route!.distance //RoutesArray.routeArray[indexPath.row].distance ?? ""
        cell.durationValueLabel.text = route!.duration //RoutesArray.routeArray[indexPath.row].duration ?? ""

        do {
            let decodedCoordinates = try JSONDecoder().decode([CLLocationCoordinate2D].self, from: route!.coordinates!)
            print("decodedCoordinates are: \(decodedCoordinates)")
            let geodesic = MKGeodesicPolyline(coordinates: decodedCoordinates, count: decodedCoordinates.count)
            cell.map.add(geodesic)
            cell.map.setRegion(MKCoordinateRegionForMapRect(geodesic.boundingMapRect), animated: true)
        } catch {
            print(error)
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
        return true
    }


    @IBAction func MyRoutesButton(_ sender: UIButton) {

        performSegue(withIdentifier: "newRouteSegue", sender: self)
    }


    // RENDER OVERLAYS
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if overlay is MKCircle {
            let renderer = MKCircleRenderer(overlay: overlay)
            renderer.fillColor = UIColor.black.withAlphaComponent(0.1)
            renderer.strokeColor = UIColor.blue
            renderer.lineWidth = 2
            return renderer
        } else if overlay is MKPolyline {
            let renderer = MKPolylineRenderer(overlay: overlay)
            renderer.strokeColor = UIColor.orange
            renderer.lineWidth = 3
            return renderer
        } else if overlay is MKPolygon {
            let renderer = MKPolygonRenderer(polygon: overlay as! MKPolygon)
            renderer.fillColor = UIColor.black.withAlphaComponent(0.5)
            renderer.strokeColor = UIColor.orange
            renderer.lineWidth = 2
            return renderer
        }
        return MKOverlayRenderer()
    }
}

,对于cell自定义类:

import UIKit
import MapKit
import CoreLocation

class RouteCell: UICollectionViewCell, MKMapViewDelegate {

    @IBOutlet weak var map: MKMapView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var titleValueLabel: UILabel!
    @IBOutlet weak var distanceLabel: UILabel!
    @IBOutlet weak var distanceValueLabel: UILabel!
    @IBOutlet weak var durationLabel: UILabel!
    @IBOutlet weak var durationValueLabel: UILabel!

 }

1 个答案:

答案 0 :(得分:0)

感谢@vadian为我指出正确的方向。在定义cell属性时,我缺少将mapView delegate声明为cell的想法。 因此我刚刚在cell.map.delegate = self函数中添加了cellForItemAt,现在它可以正常工作了。 再次感谢。