Передача текущего заголовка аннотации в
Я пытаюсь передать текущий заголовок аннотации в функцию detailAiportViewIn(). Пока код позволяет нажимать на путевую точку, и название аэропорта отображается в виде аннотации. Когда нажата аннотация, запускается функция detailAiportViewIn, и появляется представление.
Проблема, с которой я сталкиваюсь, заключается в установке переменной для текущего заголовка аннотации (той, которая выбрана), чтобы я мог передать ее в функцию detailAiportViewIn().
Причина в том, что я могу снова запросить Firestore и получить всю необходимую информацию для аэропорта.
Я приложил урезанную версию моего кода ниже.
class AirportMapViewController: UIViewController, MGLMapViewDelegate, CLLocationManagerDelegate {
}
@IBOutlet var detailedAirportView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let mapView = MGLMapView(frame: view.bounds)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.styleURL = URL(string: "mapbox://styles/jamesfergus/cjsluocim1i2p1flys3vrg4cx")
mapView.tintColor = .lightGray
mapView.logoView.isHidden = true
mapView.attributionButton.isHidden = true
mapView.setCenter(CLLocationCoordinate2D(latitude: 54.6895602,longitude: -4.0452999),zoomLevel: 4, animated: false)
mapView.delegate = self
mapView.showsUserHeadingIndicator = true
view.addSubview(mapView)
var airportArray = [CLLocationCoordinate2D()]
let db = Firestore.firestore()
_ = db.collection("AirportDatabase").getDocuments { (snapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in snapshot!.documents {
let airportName = document.documentID
let latitude = document.get("latitude") as! Double
let longitude = document.get("longitude") as! Double
print(airportName, latitude, longitude)
let aircraftCoordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
airportArray.append(aircraftCoordinates)
var pointAnnotations = [MGLPointAnnotation]()
let point = MGLPointAnnotation()
point.coordinate = aircraftCoordinates
point.title = (airportName)
pointAnnotations.append(point)
mapView.addAnnotations(pointAnnotations)
}
}
}
let indicatorSize: CGFloat = 70
let indicatorFrame = CGRect(x: (view.frame.width-indicatorSize)/2, y: (view.frame.height-indicatorSize)/2, width: indicatorSize, height: indicatorSize)
activityIndicator = NVActivityIndicatorView(frame: indicatorFrame, type: .lineScale, color: UIColor.white, padding: 20.0)
activityIndicator.backgroundColor = UIColor.black
locationManager.requestWhenInUseAuthorization()
activityIndicator.startAnimating()
if(CLLocationManager.locationServicesEnabled()){
locationManager.delegate = self as CLLocationManagerDelegate
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
func detailedAiportViewIn() {
self.view.addSubview(detailedAirportView)
detailedAirportView.center = self.view.center
detailedAirportView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
detailedAirportView.alpha = 0
view.addSubview(activityIndicator)
UIView.animate(withDuration: 0.4) {
self.airportVisualEffectView.effect = self.effect
self.detailedAirportView.alpha = 1
self.detailedAirportView.transform = CGAffineTransform.identity
}
}
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation, didFinishLoading style: MGLStyle) -> MGLAnnotationView? {
guard annotation is MGLPointAnnotation else {
return nil
}
if let source = style.source(withIdentifier: "composite") {
let layer = MGLFillExtrusionStyleLayer(identifier: "buildings", source: source)
layer.sourceLayerIdentifier = "building"
// Filter out buildings that should not extrude.
layer.predicate = NSPredicate(format: "extrude == 'true'")
// Set the fill extrusion height to the value for the building height attribute.
layer.fillExtrusionHeight = NSExpression(forKeyPath: "height")
layer.fillExtrusionOpacity = NSExpression(forConstantValue: 0.75)
layer.fillExtrusionColor = NSExpression(forConstantValue: UIColor.white)
// Insert the fill extrusion layer below a POI label layer. If you aren’t sure what the layer is called, you can view the style in Mapbox Studio or iterate over the style’s layers property, printing out each layer’s identifier.
if let symbolLayer = style.layer(withIdentifier: "poi-scalerank3") {
style.insertLayer(layer, below: symbolLayer)
} else {
style.addLayer(layer)
}
}
let reuseIdentifier = "\(annotation.coordinate.longitude)"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)
if annotationView == nil {
annotationView = CustomAnnotationView(reuseIdentifier: reuseIdentifier)
annotationView!.bounds = CGRect(x: 0, y: 0, width: 15, height: 15)
let hue = CGFloat(annotation.coordinate.longitude) / 100
annotationView!.backgroundColor = UIColor(hue: hue, saturation: 0.5, brightness: 1, alpha: 1)
}
return annotationView
}
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}
func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) {
# This is where I open the Aiport View when the annotation is pressed
detailedAiportViewIn()
}
class CustomAnnotationView: MGLAnnotationView {
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.width / 2
layer.borderWidth = 2
layer.borderColor = UIColor.white.cgColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
let animation = CABasicAnimation(keyPath: "borderWidth")
animation.duration = 0.1
layer.borderWidth = selected ? bounds.width / 4 : 2
layer.add(animation, forKey: "borderWidth")
}
}
}
Снимок экрана исходного вида при нажатии на путевую точку
Снимок экрана подробного представления при нажатии на аннотацию
Заранее спасибо!