Как вызвать аннотацию карты при просмотре коллекции в iOS Swift?

В моем проекте я использую карту MK и представление uicollection. В представлении карты показаны аннотации карты местоположения ближайших друзей пользователя на основе текущего местоположения пользователя. В представлении коллекции то же, что и имя местоположения друзей пользователя, и расстояние отображаются в представлении UICollection. (Примечание: для коллекции я использовал библиотеку cocopod UPCarouselFlowLayout)

Здесь я хочу выделить маркер аннотации карты, ближайший к текущему местоположению пользователя, и при этом аннотация карты коллекции должна быть вызвана и выбрана на карте.

Вот код, который я пробовал для ближайшего местоположения друга пользователя и просмотра коллекции:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        let pin = mapView.view(for: annotation) ?? MKAnnotationView(annotation: annotation, reuseIdentifier: nil)
        pin.image = UIImage(named: "carIcon")
        userPinView = pin
        return pin

    }

    let annotationIdentifier = "AnnotationIdentifier"
    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)

    if annotationView == nil {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
    }
    else {
        annotationView!.annotation = annotation
    }

    print("Get parking array count",parkingTypeArray.count)
    if parkingTypeArray.count > 0 {

        print("parking ty \(parkingTypeArray)")
        //

        for cameraa in parkingTypeArray.enumerated() {

            if cameraa.element == "Free" {

                let pinImage = UIImage(named: "free")
                annotationView!.image = pinImage

            }else if cameraa.element == "Paid" {

                let pinImage = UIImage(named: "paid")
                annotationView!.image = pinImage

            }
        }
    }

    return annotationView
  }

Здесь код для просмотра коллекции:

     //UICollection view - Location for parking car and street name
     extension HomeViewController : UICollectionViewDataSource, UICollectionViewDelegate {

       func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return cameraDetails.count
    }

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

         let cell = nearestCurrentLocationCollection.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! nearestLocationCollectionViewCell

    if self.cameraImageArray.count > 0 {

        cell.locationImage.sd_setImage(with: URL(string: 
      self.cameraImageArray[indexPath.row]))
        print("get location image",URL(string: 
        self.cameraImageArray[indexPath.row]))
    }

    if self.cameraDetails.count > 0 {

        cell.locationName.text = self.cameraDetails[indexPath.row]

    }
     //            cell.locationDistance.text = locationDistance[indexPath.row]

     if distanceArray.count > 0 {

        cell.locationDistance.text = String(format: " Distance : %.2f ", distanceArray[indexPath.row]/1000)

    }

      //            self.activityIndicator.stopAnimating()
      //            self.activityIndicator.isHidden = true

        return cell
    }

      func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
     moveMapPage()
       }

     fileprivate var pageSize: CGSize {
    let layout = self.nearestCurrentLocationCollection.collectionViewLayout as! UPCarouselFlowLayout
    var pageSize = layout.itemSize
    if layout.scrollDirection == .horizontal {
        pageSize.width += layout.minimumLineSpacing
    } else {
        pageSize.height += layout.minimumLineSpacing
    }
    return pageSize
    }

   func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let layout = nearestCurrentLocationCollection.collectionViewLayout as! UPCarouselFlowLayout
    let pageSide = (layout.scrollDirection == .horizontal) ? self.pageSize.width : self.pageSize.height
    let offset = (layout.scrollDirection == .horizontal) ? scrollView.contentOffset.x : scrollView.contentOffset.y
    currentPage = Int(floor((offset - pageSide / 2) / pageSide) + 1)
    print("currentpage::::\(self.currentPage)")


        if let selectedAnnotation = mapView.selectedAnnotations.first {
            // Ignore if correspondent annotation is already selected
            if 
   selectedAnnotation.isEqual(self.mapView.annotations[currentPage]) {

    self.mapView.selectAnnotation(self.mapView.annotations[currentPage], animated: true)
            }
        }


   }


 }

person PvDev    schedule 11.08.2018    source источник
comment
Получаете ли вы какую-либо другую информацию об аннотации, такую ​​как заголовок или что-либо еще, кроме текущей страницы?   -  person Nikunj Kumbhani    schedule 11.08.2018
comment
нет .. я не получил никакой ошибки. Верно ли выше?   -  person PvDev    schedule 11.08.2018


Ответы (1)


Попробуйте так, у меня работает

UICollectionView Метод делегирования

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    for annotations_item in mapView.annotations{

       if annotations_item.title == Arr_Map_Data[indexPath.row].Title{
                 self.mapView.selectAnnotation(annotations_item, animated: true)
       }

    }
}

Метод делегата MapView

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

    // first ensure that it really is an EventAnnotation:
    // Note :- Here get your Annotation I used MyPointAnnotation custom class that's why use that

    if let eventAnnotation = view.annotation as? MyPointAnnotation {

            if let index = self.Arr_Map_Comparables.index(of: eventAnnotation.obj!){
                let indexPath = IndexPath(row: index, section: 0)
                collectionView.scrollToItem(at: indexPath, at: .top, animated: true)
            }
    }
}
person Nikunj Kumbhani    schedule 11.08.2018
comment
@PvDev, откуда вы хотите выбрать анимацию аннотаций. Я должен сделать это с помощью выбранного метода. - person Nikunj Kumbhani; 11.08.2018
comment
будет ли это работать в представлении коллекции при пролистывании ячеек. - person PvDev; 11.08.2018
comment
Для просмотра коллекции Жест смахивания Попробуйте это stackoverflow.com/a/38369367/10150796 - person Nikunj Kumbhani; 11.08.2018
comment
извините, не коллекция салфетки. в то время как выбранный индекс просмотра коллекции прокрутки должен выбирать аннотацию карты - person PvDev; 11.08.2018
comment
@PvDev Вы хотите, чтобы аннотация «Отображать карту» была выбрана в выбранной ячейке представления коллекции и прокручивалась до ячейки представления коллекции для выбранной аннотации карты, верно? - person Nikunj Kumbhani; 11.08.2018
comment
точно .. извините за мой плохой английский - person PvDev; 11.08.2018
comment
Давайте продолжим обсуждение в чате. - person Nikunj Kumbhani; 11.08.2018