I am using the custom MKAnnotationView
. I use the autolayouts
which are working fine, but the position(frame) of annotation view is not appropriate.
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)
{
if view.annotation is MKUserLocation
{
return
}
let starbucksAnnotation = view.annotation as! LiquorLocation
let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil)
let calloutView = views?[0] as! CustomCalloutView
calloutView.labelLiquorShopName.text = starbucksAnnotation.title
calloutView.labelLiquorShopAddress.text = starbucksAnnotation.address
calloutView.labelLiquorShopAwayDistance.text = starbucksAnnotation.locationKmAway
calloutView.imageViewLiquorShop.image = starbucksAnnotation.liquorShopIcon
calloutView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(calloutView)
mapView.setCenter((view.annotation?.coordinate)!, animated: true)
}
What I am doing wrong? I want to center the annotation view at the top of the pin.
Autolayouts
again save my day. I add the layout constraint between my calloutview and view(MKAnnotationView). I write below lines underneath view.addSubview(calloutView)
in didSelect
method.
let horizontalConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let verticalConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
let widthConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: calloutView.frame.size.width)
view.addConstraints([horizontalConstraint, verticalConstraint, widthConstraint])