我想添加一个按钮,当用户点击标记时,该按钮将显示在注释的右侧。这是我目前正在做的事情。
这是我的ViewDidLoad
//Retrieve the existing JSON from document directory
let defaults = UserDefaults.standard
let fileUrl = defaults.url(forKey: "pathForJSON")
do {
let jsonData = try Data(contentsOf: fileUrl!, options: [])
let myJson = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [Dictionary<String,AnyObject>]
// print out the content
// print("My JSON: ", myJson)
createAnnotation(locations: myJson)
} catch {
print(error)
}
我的createAnnotation函数。
func createAnnotation(locations: [Dictionary<String, AnyObject>]) {
for location in locations {
let annotation = MKPointAnnotation()
annotation.title = location["name"] as? String
let lat = (location["latitude"] as! NSString).doubleValue
let lon = (location["longitude"] as! NSString).doubleValue
annotation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
mapView.addAnnotation(annotation)
// print(annotation)
}
}
答案 0 :(得分:0)
尝试以下代码
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView?.canShowCallout = true
let rightButton: AnyObject! = UIButton(type: UIButton.ButtonType.detailDisclosure)
pinView?.rightCalloutAccessoryView = rightButton as? UIView
}
else {
pinView?.annotation = annotation
}
return pinView
}
别忘了设置mapView的委托
mapView.delegate = self
答案 1 :(得分:0)
顺便说一句,如果定位到iOS 11或更高版本,则可以进一步简化此操作,特别是:
完全删除您的mapView(_:viewFor:)
;
注册默认的注释视图类;
定义一个注释视图类,该类根据需要配置注释及其标注。
例如:
class CustomAnnotationView: MKPinAnnotationView {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
canShowCallout = true
rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
而且,在您的视图控制器中:
override func viewDidLoad() {
super.viewDidLoad()
mapView.register(CustomAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
}