我有一个CollectionView
,显示保存到CoreData
的所有跟踪路线。除了在细胞内的地图上缺少poly line
之外,它都在工作。我以为是因为我忘了导入CoreLocation
并将它的委托分配给ViewCOntroller' but it is still not showing up after adding it. In
cellconfiguration I print the array from fetched object and it prints it correctly. In my main
MapViewControlleri 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
custom类:
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!
}
感谢@vadian让我指出正确的方向。我缺少在定义cell
attributes时将mapView delegate
声明为cell
。所以我只是在cell.map.delegate = self
function中添加了cellForItemAt
,现在它正常工作。再次感谢。