gpt4 book ai didi

ios - Swift - MKPointAnnotation 自定义图钉图像

转载 作者:行者123 更新时间:2023-11-28 07:45:14 28 4
gpt4 key购买 nike

我使用的是 Swift 3 和 Xcode 10 beta 3,我需要为 map 上的图钉使用自定义图像。我需要避免使用红色注释图钉并使用我为此制作的一些自定义 Logo 。我尝试了在堆栈上找到的所有解决方案,但没有任何帮助。这是我的代码:

import UIKit
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var map: MKMapView!

var locationManager: CLLocationManager!

override func viewDidLoad() {
super.viewDidLoad()
self.locationManager = CLLocationManager()
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()

//let span:MKCoordinateSpan = MKCoordinateSpanMake(0.1, 0.1)
let locationANTOMI:CLLocationCoordinate2D = CLLocationCoordinate2DMake(45.4509339, 9.1713609)
let locationANTOTO:CLLocationCoordinate2D = CLLocationCoordinate2DMake(45.06666, 7.68826)
//let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
//map.setRegion(region, animated: true)
let annotationANTOMI = MKPointAnnotation()
annotationANTOMI.coordinate = locationANTOMI
annotationANTOMI.title = "ANTONIOLI MILANO"

map.addAnnotation(annotationANTOMI)

let annotationANTOTO = MKPointAnnotation()
annotationANTOTO.coordinate = locationANTOTO
annotationANTOTO.title = "ANTONIOLI TORINO"
map.addAnnotation(annotationANTOTO)
}
}

我应该怎么做?

最佳答案

我通常这样做的方式是创建一个新的 swift 文件,它将成为您继承自 MKAnnoatation 的自定义注释。下面的例子

import MapKit

class MyAnnotation: NSObject, MKAnnotation {
let title: String?
let subtitle: String?
let coordinate: CLLocationCoordinate2D
var image: UIImage? = nil

init(title: String, subtitle: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
//self.image
super.init()
}
}

您需要在 CLCoordinate 是强制性的地方初始化您的注释。然后使用您的自定义图像设置图像属性。 MyAnnotation.image = "myImage.png"。然后,您需要将注释添加到 map View mapView.addAnnotations(MyAnnotation)。我还从 MKMapViewDelegate 中实现了下面的方法(确保你在你的类中继承了它)。这是为了让用户可以点击注释并接收有关它的信息。希望这会有所帮助。

在你的 View Controller 中:

let marker = MyAnnotation(title: "title" as! String, subtitle: "subtitle" as! String, coordinate: CLLocationCoordinate2D(latitude: latitude, longitude: longitude))
marker.image = UIImage("my image.png")
self.mapView.addAnnotations(marker)

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? MyAnnotation {
let identifier = "identifier"
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.image = annotation.image //add this
annotationView?.canShowCallout = true
annotationView?.calloutOffset = CGPoint(x: -5, y: 5)
annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView
return annotationView
}
return nil
}

关于ios - Swift - MKPointAnnotation 自定义图钉图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51236577/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com