如何在添加的 XIB 视图中捕捉按钮的点击(注解)

How to catch the click on the button in added XIB view (annotation)

1) 我有 ViewController 和 MapKit

1.1) 我在地图上添加了一些图钉

class ViewController: UIViewController, MKMapViewDelegate

2) 我为自定义引脚标注和注释编写了新的 类

class CustomPointAnnotation: MKPointAnnotation {

class CustomCalloutView: UIView {

3) 我已经为我的自定义 pin 标注创建了 .xib

4) 我在我的 .xib 中创建了按钮,这个按钮必须做一些事情,例如

    @IBAction func clickTest(sender: AnyObject) {
    print("aaaaa")
}

5) 这个按钮不起作用

这个通常是怎么练习的?我想让我的按钮工作。 按钮是蓝色的:

您可以在 Github 上看到的所有项目:https://github.com/genFollowMe1/forStack 谢谢,对不起英文)

您必须这样做的方法是将您的 .xib 中的按钮引用到关联的 .swift 文件中。

在你的 ViewController 中你做这样的事情 :

let button:UIButton!

[...]

button.targetForAction("tappedButton:", withSender: self)

func tappedButton() {
    print("Taped !")
}

对于 Objective C: https://github.com/nfarina/calloutview

更新

对于swift

子类化 MKAnnotationView 以进行自定义调用并覆盖 hitTest: 和 pointInside: 方法。

import UIKit
import MapKit

class CustomCalloutView: MKAnnotationView {

@IBOutlet weak var name: UILabel!

@IBAction func goButton(sender: AnyObject) {

    print("button clicked sucessfully")
}

override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
    let hitView = super.hitTest(point, withEvent: event)
    if hitView != nil {
        superview?.bringSubviewToFront(self)
    }
    return hitView
}

override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
    let rect = self.bounds
    var isInside = CGRectContainsPoint(rect, point)
    if !isInside {
        for view in subviews {
            isInside = CGRectContainsPoint(view.frame, point)
            if isInside {
                break
            }
        }
    }
    return isInside
}
}