Подключение аннотаций MapKit к табличному представлению - PullRequest
0 голосов
/ 12 ноября 2018

У меня есть контроллер вида, где нижняя половина - это таблица, а верхняя - карта. Когда он загружается, я вызываю API для получения ближайших мест и загружаю их в массив. После загрузки массива я перебираю массив, чтобы установить аннотацию для lat, lon и name каждого местоположения, и этот же массив является данными для табличного представления. То, что я пытаюсь сделать, это соединить ячейку таблицы и аннотацию.

Когда кто-то касается таблицы, я хочу, чтобы соответствующая аннотация была выбрана с вызовом для ее выбора. Когда кто-то нажимает на аннотацию, я хочу, чтобы табличное представление отображало связанную ячейку в табличном представлении и выделяло ее. Я исследовал и обнаружил, что функция mapView didSelect для обработки выбранной аннотации, но я не знаю, как (или если вы можете) соединить 2. Прямо сейчас я подделываю это, помещая положение массива в подзаголовок аннотации, и это позволяет мне прочитать все подробности с этой позиции, но мне кажется, что это неправильно.

...// load places into an array
            curBlipPlace.name = yelp.name
            curBlipPlace.distance = yelp.distance
            curBlipPlace.address1 = yelp.address1
            curBlipPlace.lat = yelp.lat
            curBlipPlace.lon = yelp.lon
            curBlipPlace.yelpId = yelp.yelpId
            curBlipPlace.yelp = yelp
            curBlipPlace.yelpArrayPosition = yelp.arrayPosition
            self.blipPlaces.append(curBlipPlace)

..// After filling array, sort it, loop to load annotations, and load to table
            self.blipPlaces.sort { $0.distance ?? 9999 < $1.distance ?? 9999 }
            for i in 0..<self.blipPlaces.count {
                if let lat = self.blipPlaces[i].lat, let lon = self.blipPlaces[i].lon {
                    let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                    let annotation = MKPointAnnotation()
                    annotation.coordinate = coordinate
                    annotation.title = self.blipPlaces[i].name
                    annotation.subtitle = String(i)

                    self.map.addAnnotation(annotation)
                }
            }

            self.PlaceTableView.reloadData()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = PlaceTableView.dequeueReusableCell(withIdentifier: "fileCell", for: indexPath) as! BlipFileTVCell
    cell.placeLabel.text = "\(indexPath.row): \(blipPlaces[indexPath.row].name) - \(blipPlaces[indexPath.row].distance ?? 999)"
    return cell
}

..// Rube Goldberg way of connecting table cell and annotation by forcing array position into subTitle
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    print("CLICKED: \(String(describing: view.annotation?.title))")
    if let tempString = (view.annotation?.subtitle) as? String {
        print("ok... \(tempString)")
        if let tempInt = Int(tempString) {
            print(self.blipPlaces[tempInt].name)
        }
    }
}

Есть ли лучший способ соединить аннотацию и ячейку таблицы? Есть ли способ, чтобы касание ячейки активировало аннотацию?

Кроме того, поскольку постукивающая аннотация может быть последней ячейкой таблицы, есть ли способ «переместить» ячейку таблицы вверх, если она находится за пределами экрана? Если кто-то выбирает аннотацию для последнего элемента в списке, есть ли способ заставить ячейку таблицы «прокрутиться», чтобы ее можно было просматривать, а не за пределами экрана?

-дан

1 Ответ

0 голосов
/ 12 ноября 2018

Реализация пользовательской аннотации.

class CustomAnnotation: MKPointAnnotation {
    var index: Int!
}

Добавление пользовательской аннотации в mapView.

let annotation = CustomAnnotation()
annotation.coordinate = coordinate
annotation.title = "title"
annotation.subtitle = "subtitle"
annotation.index = 0 // 0...n
self.mapView.addAnnotation(annotation)

Вы можете получить index в mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView).

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let annotation = view.annotation as? CustomAnnotation {
        print(annotation.index)
        // Get the cell by index
        // You can use `cellForRowAtIndexPath:`
        // Then select the cell
    }
}

РЕДАКТИРОВАНИЕ:

// when the table view is clicked 
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    for annotation in mapView.annotations {
        if let annotation = annotation as? CustomAnnotation, annotation.index == indexPath.row {
            // select annotation and show callout
            mapView.selectAnnotation(annotation, animated: true)
        }
    }
}
...