我很难显示自定义注释视图。具体来说,我试图设置一个名为“pin”的图像作为新的地图引脚。默认引脚总是显示。我已经做了几个小时的小改动,例如将“pin”改为“pin.png”,并改变了方法的结构。这是我的。你可以看看有什么突出的东西吗?无法创建自定义MKAnnotationView
感谢您的帮助!
注释类:
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")
}
}
AnnotationView类:
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))
}
}
的MapView:viewFor:方法:
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.delgate = self'?我没有看到那行 –
检查你是否在名称销的资产中的图像,对我来说你的代码工作,但它不是正确的方式做到这一点 –
@ReinierMelian设置mapview委托工作!谢谢!但它引入了一些意想不到的行为您的位置的默认注释现在也被设置为“pin”图像。 –