如何在添加的XIB视图(注释)中捕获按钮上的单击

时间:2016-04-08 12:21:24

标签: ios swift mapkit

1)我有ViewController和MapKit

1.1)我在Map

中添加了一些引脚
class ViewController: UIViewController, MKMapViewDelegate

2)我为自定义引脚标注和注释

编写新类
class CustomPointAnnotation: MKPointAnnotation {

class CustomCalloutView: UIView {

3)我为自定义引脚标注创建了.xib enter image description here

4)我在.xib中创建了按钮,此按钮必须执行某些操作,例如

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

5)此按钮无法正常工作

通常的做法是什么?我想让我的按钮工作。 按钮是蓝色的: enter image description here

您可以在Github上看到的所有项目:https://github.com/genFollowMe1/forStack 谢谢,抱歉英语)

2 个答案:

答案 0 :(得分:3)

目标C的

https://github.com/nfarina/calloutview

<强>更新

for 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
}
}

答案 1 :(得分:0)

您必须这样做才能将.xib中的按钮引用到相关的.swift文件中。

在ViewController中,你可以这样做:

let button:UIButton!

[...]

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

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