创建自定义 MKA 注释视图时出现问题



我很难显示自定义注释视图。具体来说,我正在尝试将名为"pin"的图像设置为新的地图引脚。始终显示默认引脚。几个小时以来,我一直在做一些小的更改,但无济于事,例如将"pin"更改为"pin.png"以及更改mapView:viewFor方法的结构。这是我所拥有的。你能不能看看,看看有什么突出的?

感谢您的任何帮助!

注释类:

class Annotation: NSObject, MKAnnotation {
dynamic var coordinate : CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(location coord:CLLocationCoordinate2D) {
self.coordinate = coord
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

注释视图类:

class AnnotationView : MKAnnotationView {
override init(annotation:MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation,
reuseIdentifier: reuseIdentifier)
let im = UIImage(named: "pin")!
self.frame = CGRect(x: 0, y: 0, width: im.size.width / 3.0 + 5, height: im.size.height / 3.0 + 5)
self.centerOffset = CGPoint(x: 0, y: -20)
self.isOpaque = false
}
required init (coder: NSCoder) {
fatalError("NSCoding not supported")
}
override func draw(_ rect: CGRect) {
let im = UIImage(named: "pin")!
im.draw(in: self.bounds.insetBy(dx: 5, dy: 5))
}
}

地图视图:查看对象: 方法:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var v : MKAnnotationView! = nil
let ident = "pin"
v = mapView.dequeueReusableAnnotationView(withIdentifier: ident)
if v == nil {
v = AnnotationView(annotation: annotation, reuseIdentifier: ident)
v.canShowCallout = true
}
v.annotation = annotation
return v
}

其他相关方法:

@IBAction func submitDog(_ sender: Any) {
let newDog = Dog(name: newDogName.text!, score: 11, picture: image!, location: location!)
dogs.append(newDog)
print(dogs.last!)
UIView.animate(withDuration: 0.5, animations: {
}) { _ in
self.newDogView.animation = "slideUp"
self.newDogView.animate()
self.newDogView.isHidden = true
self.newDogName.text = ""
self.map.isUserInteractionEnabled = true
}
dropNewPin(locatedAt: dogs.last!.location, name: dogs.last!.name, rate: dogs.last!.score)
}
func dropNewPin(locatedAt: CLLocation, name: String, rate: Int) {
let annotation = Annotation(location: CLLocationCoordinate2D(latitude: locatedAt.coordinate.latitude, longitude: locatedAt.coordinate.longitude))
annotation.title = name
annotation.subtitle = "(rate)/10"
self.map.addAnnotation(annotation)
}

首先,您需要将视图控制器添加为映射的委托

self.mapView.delegate = self

之后,我建议您使用MKAnnotationView而不是使用自定义绘图修改和添加图像,如果您需要自定义注释视图,则需要添加xib文件和自定义类作为文件所有者并进行适当的调整

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
//to avoid make a custom Annotation view for your user location
if(annotation is MKUserLocation){
return nil
}
let ident = "pin"
var v = mapView.dequeueReusableAnnotationView(withIdentifier: ident)
if v == nil {
v = MKAnnotationView(annotation: annotation, reuseIdentifier: ident)
v?.image = UIImage(named: "pin")
v?.canShowCallout = true
}
v?.annotation = annotation
return v
}

最新更新