xcode swift map marker点击显示设置
时间: 2023-07-31 10:05:31 浏览: 50
要在 Xcode 中使用 Swift 在地图上显示标记,并在点击标记时显示弹出窗口,可以使用 MapKit 框架中的 MKMapView 和 MKAnnotationView 类。
首先,需要定义一个实现了 MKAnnotation 协议的类来表示地图上的标记:
```
import MapKit
class MyAnnotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(coordinate: CLLocationCoordinate2D, title: String?, subtitle: String?) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
}
}
```
然后,在 ViewController 中添加 MKMapView,并设置其 delegate 属性为 self:
```
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
// 添加标记
let annotation = MyAnnotation(coordinate: CLLocationCoordinate2D(latitude: 37.33182, longitude: -122.03118), title: "Apple Inc.", subtitle: "Cupertino")
mapView.addAnnotation(annotation)
}
// 实现 MKMapViewDelegate 中的方法
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let annotation = annotation as? MyAnnotation else {
return nil
}
let identifier = "MyAnnotationView"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.canShowCallout = true
annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
} else {
annotationView?.annotation = annotation
}
return annotationView
}
// 点击详情按钮时触发
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if let annotation = view.annotation as? MyAnnotation {
let alertController = UIAlertController(title: annotation.title, message: annotation.subtitle, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
}
```
在上面的代码中,我们首先在 viewDidLoad 方法中添加了一个 MyAnnotation 标记,并将其添加到 mapView 中。然后,我们实现了 MKMapViewDelegate 中的 viewFor 方法,在其中创建了一个 MKPinAnnotationView,并设置了它的 canShowCallout 属性为 true,表示可以显示弹出窗口,并设置了它的 rightCalloutAccessoryView 属性为一个 UIButton,表示在弹出窗口的右侧添加一个详情按钮。
最后,我们实现了 MKMapViewDelegate 中的 calloutAccessoryControlTapped 方法,当用户点击详情按钮时,会触发这个方法,我们在其中创建了一个 UIAlertController,显示标记的标题和副标题,并在其中添加了一个 OK 按钮来关闭弹出窗口。
这样,当我们运行应用程序时,在地图上就会显示一个名为 "Apple Inc." 的标记,并且当我们点击这个标记时,就会显示一个弹出窗口,显示标记的标题和副标题。