在MapView上显示注释,并选择collectionView单元格

时间:2020-06-08 14:00:21

标签: ios swift mapkit mapkitannotation

我有一个程序,该程序应该根据所选的collectionView单元格在地图上显示注释。但是目前,当尝试选择collectionView单元时,地图上没有任何内容。

这是代码。

import UIKit
import MapKit

struct PlacesOnMap {
var name: String
var latitude: Double
var longitude: Double

init(name: String, latitude: Double, longitude: Double) {
self.name = name
self.latitude = latitude
self.longitude = longitude
}
}

class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, MKMapViewDelegate {

@IBOutlet weak var mapView1: MKMapView!
var placesVal = [PlacesOnMap(name: "place 1", latitude: 12.9716, longitude: 77.5946),
                 PlacesOnMap(name: "place 2", latitude: 12.2958, longitude: 76.6394),
PlacesOnMap(name: "place 3", latitude: 11.4102, longitude: 76.6950)
]
var buildings = [PlacesOnMap(name: "buildings 1", latitude: 12.9716, longitude: 77.5946),
PlacesOnMap(name: "buildings 2",  latitude: 12.2958, longitude: 76.6394)
]
var recreation = [PlacesOnMap(name: "recreation 1", latitude: 28.54693, longitude: -81.393071),
PlacesOnMap(name: "recreation 2", latitude: 28.538523, longitude: -81.385399),
PlacesOnMap(name: "recreation 3", latitude: 28.542817, longitude: -81.378117),
PlacesOnMap(name: "recreation 4", latitude: 28.538985, longitude: -81.404694)
]

let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
var items = ["Places", "Buildings", "Recreations"]
var displayCategoryText: String = ""


override func viewDidLoad() {
    super.viewDidLoad()

     mapView1?.delegate = self
}

// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.items.count
}

// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

    // Use the outlet in our custom class to get a reference to the UILabel in the cell
    cell.myLabel.text = self.items[indexPath.item]
    cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
    return cell
}

// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    displayCategoryText = String(indexPath.item)
    checkDisplayCategoryText()
}

func checkDisplayCategoryText() {
    if displayCategoryText == "0" {
        setPlacesAnnotations()
    }
    if displayCategoryText == "1" {
        setBuildingsAnnotations()
    }
    if displayCategoryText == "2" {
        setRecreationAnnotations()
    }
}

func setPlacesAnnotations() {
       let places = placesVal.map { placeOnMap -> MKPointAnnotation in
       let place = MKPointAnnotation()
       place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
       place.title = placeOnMap.name
       return place
       }
       mapView1?.removeAnnotations(mapView1.annotations)
       mapView1?.addAnnotations(places)
   }

   func setBuildingsAnnotations() {
       let places = buildings.map { placeOnMap -> MKPointAnnotation in
       let place = MKPointAnnotation()
       place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
       place.title = placeOnMap.name
       return place
       }
       mapView1?.removeAnnotations(mapView1.annotations)
       mapView1?.addAnnotations(places)
   }

   func setRecreationAnnotations() {
       let places = recreation.map { placeOnMap -> MKPointAnnotation in
       let place = MKPointAnnotation()
       place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude,  longitude: placeOnMap.longitude)
       place.title = placeOnMap.name
       return place
       }
       mapView1?.removeAnnotations(mapView1.annotations)
       mapView1?.addAnnotations(places)
   }


   func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
        guard let annotationTitle = view.annotation?.title else
              {
                  print("Unable to retrieve details")
               return
              }
     print("User tapped on annotation with title: \(annotationTitle!)")
   }

}
extension CollectionViewController: UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let cellsAcross: CGFloat = 3
    var widthRemainingForCellContent = collectionView.bounds.width
    if let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout {
        let borderSize: CGFloat = flowLayout.sectionInset.left + flowLayout.sectionInset.right
        widthRemainingForCellContent -= borderSize + ((cellsAcross - 1) * flowLayout.minimumInteritemSpacing)
    }
    let cellWidth = widthRemainingForCellContent / cellsAcross
    return CGSize(width: cellWidth, height: cellWidth)
}

}

class MyCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var myLabel: UILabel!

}

这是情节提要的照片。

Picture of storyboard

我将如何解决此问题,以便根据所选的集合视图单元格在mapView上显示正确的注释?

2 个答案:

答案 0 :(得分:1)

我假设您已在情节提要中正确设置了UICollectionView委托和dataSource。

选择单元格时设置:

displayCategoryText = String(indexPath.item)

,但是您对该变量不做任何事情。您需要调用一个方法,该方法可以使用该变量的值从数据模型中提取正确的信息,然后将注释添加到地图中。

答案 1 :(得分:1)

我为此苦苦挣扎了整整 3 天,并阅读了几乎所有谷歌文章,直到我找到了有帮助的一篇。

首先在 mapview(didSelect:) 中获取您的注释索引

let index = (self.mapView.annotations as NSArray).index(of: anno) *Anno 是我的自定义注释视图的 view.annotation 常量

然后,如果您希望 collectionview 通过点击注释滚动到正确的单元格,请将其添加到您的 didSelect 函数中:

let path = IndexPath(row: index, section: 0) self.collectionView.scrollToItem(at: path, at: .centralHorizo​​ntally, animation: true)

然后,在 collectionView cellForItemAt 中,我添加了以下内容:

self.mapView.selectAnnotation(self.mapView.annotations[indexPath.row], 动画:false)

这将选择与您的 mapView 注释的 indexPath.row 对应的注释!

希望有所帮助!