我想用自定义 Logo 替换默认的 MKPointAnnotation Logo 。
所以我在 MapViewController 中编写了这段代码:
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var myMap: MKMapView!
let locationManager = CLLocationManager()
var monPin:CustomPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
override func viewDidLoad() {
super.viewDidLoad()
//Mark: - Authorization
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
myMap.delegate = self
myMap.mapType = MKMapType.standard
myMap.showsUserLocation = true
let location = CLLocationCoordinate2D(latitude: 43.2885108, longitude:5.3855545000000124)
let center = location
let region = MKCoordinateRegionMake(center, MKCoordinateSpan(latitudeDelta: 0.025, longitudeDelta: 0.025))
myMap.setRegion(region, animated: true)
monPin = CustomPointAnnotation()
monPin.pinCustomImageName = "mapIcon"
monPin.coordinate = location
monPin.title = "Mon titre"
monPin.subtitle = "mon Sous titre"
pinAnnotationView = MKPinAnnotationView(annotation: monPin, reuseIdentifier: "pin")
myMap.addAnnotation(pinAnnotationView.annotation!)
}
//MARK: - Custom Annotation
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let reuseIdentifier = "pin"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier:reuseIdentifier)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
annotationView?.canShowCallout = true
} else {
annotationView?.annotation = annotation
}
let customPointAnnotation = annotation as! CustomPointAnnotation
annotationView?.image = UIImage(named: customPointAnnotation.pinCustomImageName)
return annotationView
}
其中 monPin.pinCustomImageName = "mapIcon"引用我的 xassets
但它只显示一张经典的 MKPointAnnotation 图片(这张: /image/pD82c.png )
**我认为问题在于: ** 函数 mapView 没有在任何地方调用,因为我在其中尝试了一个简单的 print("hello") ,它没有出现在控制台中,即使我删除了所有这些函数代码,它不会改变我的应用程序的任何内容。
这就是为什么我想知道如何面对这个问题。
我不能 100% 理解我的代码,因为我从一位善良的堆栈溢出用户那里获取了它,我的意思是我理解除了 mapView() 部分之外的所有代码。
最佳答案
我相信如果您使用默认设置创建了新项目,Xcode 会显示警告。 (您不应忽略任何警告。)
Instance method 'mapView(mapView:viewForAnnotation:)' nearly matches optional requirement 'mapView(_:viewFor:)' of protocol 'MKMapViewDelegate'
这行代码:
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
没有实现 Swift 3 中 MKMapViewDelegate
中声明的任何协议(protocol)方法。
快速修复功能(选择第一个)将其修复为:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
如果你的 Xcode 不能帮助你修复,你可能需要自己修复。
无论如何,通过上面所示的修复,应该调用该方法。
关于swift - MKPointAnnotation 上的自定义图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41201664/