我设计了一个自定义注释,视图看起来很好。但是在视图中有一个按钮,当我点击它时,没有发生。它应该在日志中打印一些内容。 这是Custom Annotation类中的代码。
import UIKit
import MapKit
import CoreLocation
import CoreData
class CustomAnnotation: MKPinAnnotationView, MKMapViewDelegate, CLLocationManagerDelegate {
let firmaLabel : UILabel = UILabel.init(frame:CGRect(x: 0, y: -50, width: 200, height: 50))
let infoButton = UIButton(type: .detailDisclosure)
override func setSelected(_ selected: Bool, animated: Bool)
{
super.setSelected(true, animated: animated)
firmaLabel.textAlignment = .center
firmaLabel.textColor = UIColor.white
firmaLabel.font = UIFont.init(name: "Trebuchet MS", size: 20)
firmaLabel.backgroundColor = UIColor.black
firmaLabel.layer.borderColor = UIColor.darkGray.cgColor
firmaLabel.layer.cornerRadius = 5
firmaLabel.layer.masksToBounds = true
infoButton.frame = CGRect(x: -50, y: -50, width: 50, height: 50)
infoButton.backgroundColor = UIColor.red
infoButton.layer.borderColor = UIColor.darkGray.cgColor
infoButton.layer.cornerRadius = 5
infoButton.layer.masksToBounds = true
infoButton.setTitle(">", for: UIControlState.normal)
//The code below is the way I imagine it should make it work??
infoButton.addTarget(self, action: #selector(btnClicked(_:)), for: UIControlEvents.touchUpInside)
firmaLabel.text = "Hello"
self.addSubview(firmaLabel)
self.addSubview(infoButton)
}
func btnClicked (_: UIButton) {
print("Hello world")
}
}
这是我运行项目时的样子。它看起来应该是
我以这种方式在Viewcontroller中调用自定义注释
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation
{
return nil
}
var annotationView = self.mapView.dequeueReusableAnnotationView(withIdentifier: "Pin")
if annotationView == nil{
annotationView = CustomAnnotation(annotation: annotation, reuseIdentifier: "Pin")
annotationView?.canShowCallout = false
} else {
annotationView?.annotation = annotation
}
return annotationView
}
答案 0 :(得分:0)
问题是,您正在创建一个MKPinAnnotation视图,并在其上添加两个额外的视图。你应该使用一个标注视图。在您现有的代码中,鼠标点击只会通过'在引脚上,尝试向下移动按钮,使其覆盖引脚,您将看到选择器(需要更新)将被调用。
如果您只想快速显示按钮,请考虑将其添加为这样的标注附件视图(在ViewCtrl中):
if annotationView == nil{
annotationView = CustomAnnotation(annotation: annotation, reuseIdentifier: "Pin") //Might as well be MKPinAnnotationView
annotationView?.canShowCallout = true
let infoButton = UIButton(type: .detailDisclosure)
infoButton.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
infoButton.backgroundColor = UIColor.red
infoButton.layer.borderColor = UIColor.darkGray.cgColor
infoButton.layer.cornerRadius = 5
infoButton.layer.masksToBounds = true
infoButton.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
annotationView?.leftCalloutAccessoryView = infoButton
}
然后记得添加动作:
func buttonClicked() {
print("Button Clicked")
}
结果:
编辑:看一下Apples" MapCallouts"示例代码,它们为iOS和macOS显示不同类型的注释。非常有用!