我正在更改应用程序的一部分,从在 UITableview
中显示一些商店到在 MKMapView
上显示它们,它们显示良好,但我得到的坐标为零当我选择 map 上的注释时的值。在 didAdd
中,我打印了它们,它们很好,实际上注释显示在 map 上。
自从我上次使用 MapKit 以来已经有一段时间了,我无法确定问题是否出在自定义注释类中或其他地方。你能发现我在哪里滥用它吗?
一如既往,非常感谢您的时间和帮助。
这是注释类:
class ShopAnnotation: NSObject , MKAnnotation {
var title: String?
var coordinate:CLLocationCoordinate2D
var image: UIImage?
var shopName: String?
var shopLogoUrl: String?
init(title: String, iconImage: UIImage, coordinate:CLLocationCoordinate2D, shopName: String, shopLogoUrl: String) {
self.coordinate = coordinate
self.title = title
self.shopName = shopName
self.shopLogoUrl = shopLogoUrl
self.image = iconImage
}
}
比我有一个数组,我可以从中获取值:
var availableShopsArray:[(name:String, logoUrl:String, homeLat: String, homeLong: String)] = []
然后我循环遍历它并在 map 上放置注释:
func displayShops() {
mapView.removeAnnotations(mapView.annotations)
for shop in availableShopsArray {
let coordinates: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: Double(shop.homeLat)!, longitude: Double(shop.homeLong)!)
let title = "Route Mid"
let image = UIImage(named: title)!
let shopAnn: ShopAnnotation = ShopAnnotation(title: title, iconImage: image, coordinate: coordinates, shopName: shop.name, shopLogoUrl: shop.logoUrl)
mapView.addAnnotation(shopAnn)
}
// self.availableShopsTableview.reloadData()
}
当我选择一个时,我应该从中获取值,但坐标为零:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let selectedShop = view.annotation as? ShopAnnotation else {return}
self.shopLogoUrl = selectedShop.shopLogoUrl!
self.selectedShopCoordinates.latitude = selectedShop.coordinate.latitude
self.selectedShopCoordinates.longitude = selectedShop.coordinate.longitude
self.selectedShopName = selectedShop.shopName
// calculateBookingType()
self.performSegue(withIdentifier: "bookingToCartSegue", sender: self)
}
这是viewForAnnotation
:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { // rajish version
let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "")
if annotation is MKUserLocation{
return nil
} else {
print("Annotation.coordinates are: \(String(describing: annotation.coordinate))")
// print("annotation title is: \(String(describing: annotation.title!))")
annotationView.image = UIImage(named:(annotationView.annotation?.title)! ?? "")
annotationView.canShowCallout = true
let transform = CGAffineTransform(scaleX: 0.27, y: 0.27) // alert annotation's icons size
annotationView.transform = transform
// makin allerts draggable
annotationView.isDraggable = false
return annotationView
}
}
最佳答案
奇怪的是,我将 selectedShop.cooperative
中的纬度和经度分别分配给 selectedShopCooperatives
,并且在它上面会发现 nil。
我现在将它们指定为 selectedShopCooperatives = selectedShop.coordinate
的坐标,并且不再崩溃。
为什么在单个坐标度上会发现 nil 仍然是一个谜。 任何关于原因的想法将不胜感激。 希望这能帮助其他陷入困境的人。 干杯
关于ios - 在 map Swift 上选择注释时坐标为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58934415/