我正在制作一个自定义的MKAnnotationView,我在xib内部有一个按钮,我想在其中获取何时在内部进行修饰。
尽管存在具有相同问题的问题,但它们都无法使用我的代码。我有以下内容。
class CustomCalloutView: MKAnnotationView {
var didTapGoButton: (() -> Void)?
// MARK: - Detect taps on callout
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let rect = self.bounds;
var isInside: Bool = rect.contains(point);
if(!isInside)
{
for view in self.subviews
{
isInside = view.frame.contains(point);
if isInside
{
break;
}
}
}
return isInside;
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hitView = super.hitTest(point, with: event)
if (hitView != nil)
{
self.superview?.bringSubview(toFront: self)
}
return hitView
}
@IBAction func viewEventDetails(_ sender: Any) {
didTapGoButton?()
}
func configureCell(events: Events) {
eventName.text = events.eventName
}
}
视图控制器
class EventAnnotation : MKPointAnnotation {
var myEvent:Events?
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let annotation = view.annotation else { return }
if view.annotation!.isKind(of: MKUserLocation.self){
return
}
if let eventAnnotation = view.annotation as? EventAnnotation {
let theEvent = eventAnnotation.myEvent
let customView = (Bundle.main.loadNibNamed("CustomCalloutView", owner: self, options: nil))?[0] as! CustomCalloutView;
let calloutViewFrame = customView.frame;
customView.frame = CGRect(x: -calloutViewFrame.size.width/2.23, y: -calloutViewFrame.size.height-7, width: 315, height: 298)
customView.configureCell(events: theEvent!)
customView.didTapGoButton = { [weak mapView ] in
print(theEvent?.eventName ?? "noname")
}
view.addSubview(customView)
}
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView)
{
for childView:AnyObject in view.subviews{
childView.removeFromSuperview();
}
}
因此,当我点击按钮时,没有打印任何内容!
知道我在代码中的错误在哪里吗?
我解决了它,这个想法是将自定义视图定位在pinAnnotationView图像的边界中,因为它的任何点击外侧都将被视为didSelect方法调用,所以玩框架直到检测到点击,它将在自定义视图或视图控制器中工作
customView.frame = CGRect(x: -calloutViewFrame.size.width/2.23, y: calloutViewFrame.size.height, width: 315, height: 298)
这是一个演示来说明情况
自定义固定注释按钮