Ios 从注释中获取数组索引
嗨,我想在用户点击注释时获取索引号。我有以下代码Ios 从注释中获取数组索引,ios,swift,mapkit,mapkitannotation,Ios,Swift,Mapkit,Mapkitannotation,嗨,我想在用户点击注释时获取索引号。我有以下代码 class ShopLocation: NSObject, MKAnnotation{ var identifier = "Shop location" var title: String? var subtitle: String? var coordinate: CLLocationCoordinate2D init(name:String,lat:CLLocationDegrees,long:CLLocationDegr
class ShopLocation: NSObject, MKAnnotation{
var identifier = "Shop location"
var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D
init(name:String,lat:CLLocationDegrees,long:CLLocationDegrees,addInfo:String){
title = name
coordinate = CLLocationCoordinate2DMake(lat, long)
subtitle = addInfo
}
}
class LocationList: NSObject {
var shop = [ShopLocation]()
override init(){
shop += [ShopLocation(name:"t1", lat:35.673647,long:139.727686,addInfo:"info")]
shop += [ShopLocation(name:"t2", lat:35.671928,long:139.760815,addInfo:"info")]
shop += [ShopLocation(name:"t3", lat:35.713232,long:139.793467,addInfo:"info")]
}
注释显示在地图上。我想得到索引,例如,如果t1被点击,我得到的索引是1
我不知道写什么好
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
LocationList().shop.index(of: )
}
谢谢大家! 请尝试以下代码:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let annotation = view.annotation else {
return
}
for (index, item) in LocationList().shop.enumerated() {
if let title = view.annotation?.title {
if item.name! == title! {
print(index)
break
}
}
}
请尝试以下代码:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let annotation = view.annotation else {
return
}
for (index, item) in LocationList().shop.enumerated() {
if let title = view.annotation?.title {
if item.name! == title! {
print(index)
break
}
}
}
我假设
ShopLocation
已经符合MKAnnotation
,如果不符合,则使其符合并将其传递给MKAnnotationView
的初始值设定项。这将通过view.annotation
现在您可以访问ShopLocation
实例了,我想到了两种解决方案,可以在shop
equalable
-这将启用数组的第一索引(of:)
方法(实际上是数组符合的集合的)
数组的firstIndex(其中:)
方法(实际上也是集合的:)
就个人而言,我建议采用方法1,甚至苹果公司也建议将值类型与equalable一致。符合
Equatable
有助于减少代码,并启用此处提到的索引(of:)
之外的许多其他功能。我假设ShopLocation
已经符合MKAnnotation
,如果不符合,则使其符合并将其传递给MKAnnotationView
的初始值设定项。这将通过view.annotation
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
var index = shops.index(of: view.annotation! as! ShopLocation)!
}
现在您可以访问ShopLocation
实例了,我想到了两种解决方案,可以在shop
equalable
-这将启用数组的第一索引(of:)
方法(实际上是数组符合的集合的)
数组的firstIndex(其中:)
方法(实际上也是集合的:)
equalable
有助于代码缩减,并启用除此处提到的索引(of:)
之外的许多其他功能
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
var index = shops.index(of: view.annotation! as! ShopLocation)!
}
为我做了这项工作
为我做了这项工作 您需要索引还是需要访问映射到注释视图的
ShopLocation
实例?谢谢您的评论。我需要店铺数组的索引。您需要索引还是需要访问映射到注释视图的ShopLocation
实例?谢谢您的评论。我需要shop数组的索引。这些是很多强制展开:)您好,谢谢您的代码,但我收到一个错误,说shoplocation在item.name!==标题代码>@Cristik使用可选绑定:)这些是很多强制展开:)您好,谢谢您的代码,但我收到一个错误,说shoplocation在item.name!==标题
@Cristik使用可选绑定:)请注意,您在这里进行了大量强制强制转换,如果以后条件发生变化,可能会导致应用程序崩溃。我建议使用if let
,或者guard let
构造。请注意,您在这里进行了大量强制强制转换,如果以后条件发生变化,可能会导致应用程序崩溃。我建议使用if-let
,或者guard-let
构造。