У меня есть 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!
}