我需要一个完全可自定义的MKAnnotation
标注。我已经将MKAnnotationView
和UIView
子类化了。我的代码:
class CustomAnnotationView: MKAnnotationView {
class var reuseIdentifier:String {
return "CustomAnnotationView"
}
private var calloutView:MapPinCallOut?
private var hitOutside:Bool = true
var preventDeselection:Bool {
return !hitOutside
}
convenience init(annotation:MKAnnotation!) {
self.init(annotation: annotation, reuseIdentifier: CustomAnnotationView.reuseIdentifier)
//false?
canShowCallout = true;
}
override func setSelected(selected: Bool, animated: Bool) {
let calloutViewAdded = calloutView?.superview != nil
if (selected || !selected && hitOutside) {
super.setSelected(selected, animated: animated)
}
self.superview?.bringSubviewToFront(self)
if (calloutView == nil) {
calloutView = MapPinCallOut()
}
if (self.selected && !calloutViewAdded) {
addSubview(calloutView!)
}
if (!self.selected) {
calloutView?.removeFromSuperview()
}
}
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
var hitView = super.hitTest(point, withEvent: event)
if let callout = calloutView {
if (hitView == nil && self.selected) {
hitView = callout.hitTest(point, withEvent: event)
}
}
hitOutside = hitView == nil
return hitView;
}
}
这是我的UIView
:
class MapPinCallOut: UIView {
override func hitTest(var point: CGPoint, withEvent event: UIEvent?) -> UIView? {
let viewPoint = superview?.convertPoint(point, toView: self) ?? point
let isInsideView = pointInside(viewPoint, withEvent: event)
var view = super.hitTest(viewPoint, withEvent: event)
return view
}
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
return CGRectContainsPoint(bounds, point)
}
}
我还创建了一个nib文件,并将文件的所有者更改为" MapPinCallOut
"
然后在我viewDidLoad
的{{1}}中,我添加了一个这样的图钉:
viewController
然后在我的viewForAnnotation函数中:
let location = CLLocationCoordinate2D(
latitude: 25.0336,
longitude: 121.5650
)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: location, span: span)
mapView.setRegion(region, animated: true)
let string = "title"
let annotation = CustomAnnotation(location: location, title: string, subtitle: string)
mapView.addAnnotation(annotation)
毕竟,我运行了我的代码,当我选择注释时,标注确实会出现,但它仍然是标准注释。创建自己的自定义标注视图我缺少什么?
答案 0 :(得分:0)
在pinView.canShowCallout
中将false
设为viewForAnnotation
。这可能会帮助你。