I am trying to present another view controller once the right callout button is pressed but it must go to the correct indexPath, similar to how this happens in a table view. this is where I am up to:
I have created a custom annotation like so:
class annotationCustom: NSObject, MKAnnotation {
var coordinate : CLLocationCoordinate2D
var title : NSString!
var subtitle : NSString!
var isUserAnnotation : Bool
var dataImage = [NSData]()
init(coordinate: CLLocationCoordinate2D, title: NSString!, subtitle: NSString!){
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
self.isUserAnnotation = false
}
}
and then set the viewForAnnotation like so:
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
var dqPin = "pin"
var view = mapView.dequeueReusableAnnotationViewWithIdentifier(dqPin) as? MKPinAnnotationView
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: dqPin)
view!.canShowCallout = true
var arrowBut = UIImage(named: "arrow")
var arrowButton = UIButton()
arrowButton.setImage(arrowBut, forState: UIControlState.Normal)
arrowButton.tintColor = UIColor.blackColor()
arrowButton.frame = CGRectMake(0, 0, 30, 30)
view!.rightCalloutAccessoryView = arrowButton
}
return view
}
Now I know I have to use the function:
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
if control == view.rightCalloutAccessoryView {
let sb = UIStoryboard(name: "Main", bundle: nil)
let userProfileVC = sb.instantiateViewControllerWithIdentifier("usersProfileVC") as UsersProfilesViewController
userProfileVC.profileName = annotationCustom.title // error: 'annotationCustom.Type' does not have a member named 'title'
performSegueWithIdentifier("goToUserFromMap", sender: self)
}
}
}
Can somebody fill in the gaps or help me out please.
Thanks
Instead of:
if control == annotationView.rightCalloutAccessoryView {
it should be:
if control == view.rightCalloutAccessoryView {
view is the internal, private name of the parameter and annotationView is the external name visible to the caller.
However, in this case, you don't really need to check control in the first place since your callouts have only a single control (rightCalloutAccessoryView). They don't have a leftCalloutAccessoryView so there's only one control the user could tap.
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
println("disclosure pressed on: \(view.annotation.title)")
}
By the way, is the code shown in viewForAnnotation the actual code? Because it looks like the result of the dequeueReusableAnnotationViewWithIdentifier is ignored and there is a mysterious extra closing } before the return view.
Here:
userProfileVC.profileName = annotationCustom.title
annotationCustom is the name of your class -- not the instance of it (also, convention is to start class names with a capital letter). view.annotation is the instance here. Cast it as annotationCustom to access any custom properties (though title isn't custom):
if let ac = view.annotation as? annotationCustom {
userProfileVC.profileName = ac.title
}
Related
In my app, I have a mapkit full of annotations and when one is clicked I want a new view to slide up with details on the annotation. Correct me if I'm wrong but I think you need to create a custom annotation in order to implement the didSelect() method.
The problem is that, by default, the custom annotations that pop up don't have the name of what the annotations is, like the default mapkit annotations do, and since I have around 20 annotations at a time, the user has no way of knowing what they are selecting.
Any idea as to how to add a title or label underneath the custom annotation with the name of the annotation? I don't want to make a call out that pops up above the annotation since I'm having the view slide up, filled with the annotations data.
Here is what I have:
extension ViewController : MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation { return nil }
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "pin") as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
annotationView?.animatesDrop = true
annotationView?.canShowCallout = false
} else {
annotationView?.annotation = annotation
}
return annotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
UIView.animate(withDuration: 0.2) {
// the view that will hold the annotations data
self.annotationInfoViewBottomConstraint.constant = 0
self.view.layoutIfNeeded()
}
}
}
As you can see the default annotation has the name of the location underneath, which is what I want but I want it under the "pin" looking custom annotations.
You can create a label like so:
let annotationLabel = UILabel(frame: CGRect(x: -40, y: -35, width: 105, height: 30))
annotationLabel.numberOfLines = 3
annotationLabel.textAlignment = .center
annotationLabel.font = UIFont(name: "Rockwell", size: 10)
// you can customize it anyway you want like any other label
Set the text:
annotationLabel.text = annotation.title!!
And then add to annotation view:
annotationView.addSubview(annotationLabel)
Picture of annotation with label
I also added a background and border by doing:
annotationLabel.backgroundColor = UIColor.white
annotationLabel.layer.cornerRadius = 15
annotationLabel.clipsToBounds = true
You can also change where the label is in respect to the annotation by changing the X and Y when creating the label. Negative is to the left and up, positive right and down.
Simple Solution for Name under Marker and color change:
MapKit Delegate Method: (I have used MKMarkerAnnotationView and use markerTintColor to set color)
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "pin") as? MKMarkerAnnotationView
guard let annotation = annotation as? PlaceAnnotation else {
return annotationView
}
if annotationView == nil {
annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "pin")
} else {
annotationView?.annotation = annotation
}
annotationView?.markerTintColor = annotation.pinTintColor
return annotationView
}
MKAnnotation Custom Class:
class PlaceAnnotation: NSObject, MKAnnotation {
let title: String?
let locationName: String
let discipline: String
let coordinate: CLLocationCoordinate2D
var pinTintColor: UIColor
init(id: String, title: String, locationName: String, discipline: String, coordinate: CLLocationCoordinate2D, pinTintColor: UIColor) {
self.title = title
self.locationName = locationName
self.discipline = discipline
self.coordinate = coordinate
self.pinTintColor = pinTintColor
super.init()
}
}
How to Use:
let place = PlaceAnnotation(title: "My Location", locationName: "", discipline: "", coordinate: CLLocationCoordinate2D(latitude: lat, longitude: lng), pinTintColor: UIColor.systemBlue)
map.addAnnotation(place)
You'll need to set annotationView.enabled and annotationView.canShowCallout to YES
I currently have a UIMapView with different annotations pinned for the different locations of users on the map. I'm trying to segue to the respective users profile when the annotation is clicked. Here's my code to set up the annotations:
let query = PFQuery(className: "location")
query.findObjectsInBackground { (objects, error) in
if let brandsLocation = objects {
for object in brandsLocation {
if let brandLocation = object as? PFObject {
let annotation = MKPointAnnotation()
let annotationPoint = object["geoPoint"] as! PFGeoPoint
annotation.coordinate = CLLocationCoordinate2DMake(annotationPoint.latitude, annotationPoint.longitude)
annotation.title = brandLocation["annotationTitle"] as? String
annotation.subtitle = brandLocation["annotationSubtitle"] as? String
self.map.addAnnotation(annotation)
}
}
}
}
This is where I believe the segue is supposed to happen, however it isn't doing anything for some reason.
// When user taps on the disclosure button you can perform a segue to navigate to another view controller
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView,
calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView{
performSegue(withIdentifier: "goToUserProfile", sender: view)
print(view.annotation?.title) // annotation's title
print(view.annotation?.subtitle) // annotation's subttitle
//Perform a segue here to navigate to another viewcontroller
// On tapping the disclosure button you will get here
}
}
// Here we add disclosure button inside annotation window
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
print("viewForannotation")
if annotation is MKUserLocation {
//return nil
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
//println("Pinview was nil")
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
}
let button = UIButton(type: UIButtonType.detailDisclosure) as UIButton // button with info sign in it
pinView?.rightCalloutAccessoryView = button
return pinView
}
I'd like for the segue to happen when the annotation is clicked or double clicked, and then perform a segue to that new view controller while sending the specific username info as well. I'm pretty sure I'll be able to send the user info but I just need to figure out how to make the segue happen. I think it may have to do with the fact that in the new XCode update my calloutaccessory hasn't been showing. Here's a screenshot from my app. MapView Annotation
How about using didSelect method instead of calloutAccessoryControlTapped?
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
performSegue(withIdentifier: "goToUserProfile", sender: view)
print(view.annotation?.title) // annotation's title
print(view.annotation?.subtitle) // annotation's subttitle
}
My iOS map view shows an initial annotation. I want the user to be able to click on the map and for the annotation to move to the spot where the user clicked, but to retain the non-coordinate information in the annotation (e.g. title, subtitle). The code below works, but intermittently the title and subtitle are not showing (see animation and that the name "Spot Name" sometimes doesn't show). It's unclear to me why this is occurring. If I add print statements to print spot.name and spot.title after mapView.addAnnotation, the String values are there & remain unchanged in the MKAnnotation conforming class. Also, when I click in the marker, the proper title and subtitle show in the callout, even if they weren't showing in the annotation. Grateful for any advice/corrections. Thanks!
import UIKit
import MapKit
class SpotDetailViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView!
var spot: Spot! // Spot class conforms to NSObject & MKAnnotation
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
spot = Spot()
spot.coordinate = CLLocationCoordinate2D(latitude: 42.334709, longitude: -71.170061)
spot.name = "Spot Name"
spot.address = "Spot Address, Spot Town, Spot State"
// Set initial region
let regionDistance: CLLocationDistance = 250
let region = MKCoordinateRegionMakeWithDistance(spot.coordinate, regionDistance, regionDistance)
mapView.setRegion(region, animated: true)
mapView.addAnnotation(self.spot)
}
#IBAction func mapViewTapped(_ sender: UITapGestureRecognizer) {
let annotationView = mapView.view(for: mapView.annotations[0])
let touchPoint = sender.location(in: mapView)
guard !(annotationView?.frame.contains(touchPoint))! else {
return
}
let newCoordinate: CLLocationCoordinate2D = mapView.convert(touchPoint, toCoordinateFrom: mapView)
spot.coordinate = newCoordinate
mapView.removeAnnotations(mapView.annotations)
mapView.addAnnotation(self.spot)
mapView.setCenter(spot.coordinate, animated: true)
}
}
extension SpotDetailViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifer = "Marker"
var view: MKMarkerAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifer) as? MKMarkerAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifer)
view.canShowCallout = true
view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
return view
}
}
I have tried following different tutorials to make my MKAnnotations have an accessory item that will segue to a different page when clicked; however, I cannot get the item to show. Here is the code I've come up with after reviewing different sources:
extension MapController : MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "PlaceAnnotation"
if annotation is PlaceAnnotation {
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView!.canShowCallout = true
} else {
annotationView!.annotation = annotation
}
annotationView!.leftCalloutAccessoryView = nil
annotationView!.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure)
return annotationView
}
return nil
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let place = view.annotation as! PlaceAnnotation
let placeName = place.title
print(placeName!)
let placeInfo = place.placeObject
let ac = UIAlertController(title: placeInfo?.title, message: placeInfo?.description, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
Then, to create the annotation, I have this:
for place in places {
let placeCoord = CLLocationCoordinate2D(latitude: CLLocationDegrees(place.latitude)!, longitude: CLLocationDegrees(place.longitude)!)
let annotation = PlaceAnnotation(title: place.title, coordinate: placeCoord, placeObject: place)
mapView.addAnnotation(annotation)
}
And the PlaceAnnotation class is as follows:
class PlaceAnnotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var placeObject: Location?
init(title: String, coordinate: CLLocationCoordinate2D, placeObject: Location) {
self.title = title
self.coordinate = coordinate
self.placeObject = placeObject
}
}
The only thing that displays on the annotation when clicked is the Title, but nothing else. I appreciate any help, thank you very much!
(I am working in Swift 3)
I tried your code and it works perfectly fine for me.
But when I removed say,
mapView.delegate = self
Accessory item did not show up, because the delegate is not called.
I am creating a map application which allows emojis to be attached to locations. Currently, the image is displayed above the stock apple map annotation.
I wish to hide the stock pin image while still displaying the selected emoji by the user. Is this possible?
I have this code so far to perform this:
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
//let identifier = "MyPin"
if annotation.isKindOfClass(MKUserLocation) {
return nil
}
let dictName = arrLocation[((annotation as? MyAnnotation)?.index)!]
let imgName = dictName.valueForKey("pin_img") as? String
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(imgName!)
if annotationView == nil
{
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: imgName)
annotationView!.canShowCallout = false
let name = dictName.valueForKey("name") as! String
let annot = MyAnnotation(titleName:name)
annotationView?.annotation = annot
}
else
{
annotationView!.annotation = annotation
}
let detailButton: UIButton = UIButton(type: UIButtonType.Custom)
// size and placement of emoji on map
detailButton.frame = CGRectMake(-34,-25,85,85)
detailButton.tag = ((annotation as? MyAnnotation)?.index)!
detailButton.addTarget(self, action:"emojiTap:", forControlEvents: UIControlEvents.TouchUpInside)
detailButton.setBackgroundImage(UIImage(named:(dictName.valueForKey("pin_img") as? String)!), forState: UIControlState.Normal)
annotationView!.addSubview(detailButton)
return annotationView
}
Custom annotation view
Instead of using an MKPinAnnotationView, use its superclass MKAnnotationView.
Responding to input
To respond to the user tapping on an annotation implement the mapView:didSelectAnnotation: delegate method. This delegate method is called when the annotation is tapped.
Note that you do not need to use the button inside the annotation view. This means the functionality in emojiTap: must be implemented by the mapView:didSelectAnnotationMethod:.
Example
Combining these
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation.isKindOfClass(MKUserLocation) {
return nil
}
let dictName = arrLocation[((annotation as? MyAnnotation)?.index)!]
let imgName = dictName.valueForKey("pin_img") as? String
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(imgName!)
if annotationView == nil
{
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: imgName)
let name = dictName.valueForKey("name") as! String
let annot = MyAnnotation(titleName:name)
annotationView?.annotation = annot
}
else
{
annotationView!.annotation = annotation
}
annotationView!.canShowCallout = false
return annotationView
}
func mapView(_ mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
guard let annotation = view.annotation as? MyAnnotation else {
return
}
print("tapped annotation: \(annotation.index)
// Implement the code from emojiTap: here.
}