自定义视图Xib for MKAnnotationView按钮点击

时间:2018-01-08 12:30:31

标签: ios swift swift3 mkannotationview

我正在制作一个自定义的MKAnnotationView,我在xib中有一个按钮,我想在里面进行touchedup时得到它。

尽管对同一问题存在疑问,但它们都没有使用我的代码。 我有以下内容。

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

 }
}

的ViewController

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();
        }
    }

因此,当我点击按钮时,没有任何内容正在打印!

知道我在代码中的错误在哪里?

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,我的想法是将customView放在pinAnnotationView图像的边界,因为任何一次点击都会被认为是一个didSelect方法调用,所以玩框直到检测到点击,它才能在自定义视图或viewController

    customView.frame = CGRect(x: -calloutViewFrame.size.width/2.23, y: calloutViewFrame.size.height, width: 315, height: 298)

这是一个演示情况的演示

customPinAnnotationButton