It Finally Happened. I picked up my first Mac computer in January. I am now the proud owner of a MacBook Pro 13, no touch bar and the regular keyboard. I went into the local Apple Store and tried out the newer keyboard and the older keyboard and have to say that I liked the feel of the old one better. I really didn’t like how loud the new keyboard was. But the old keyboard was good, trackpad was good (but not as good as I thought it was going to be) and the screen was nice. Overall a nice computer if expensive. But the important thing is that I could finally install XCode and build iOS apps!
And that is the subject of the this blog post. In the previous blog post, we looked at creating a custom renderer for Android. Now we will look at doing the same with iOS. With iOS, things are simpler in at least one regard: you don’t have to go get an access key for your app.
One thing I want to make clear after some questions from others. This information isn’t a whole lot different than what you can get from developer.xamarin.com. But it builds on those examples by making the custom map renderer updatable from your view model … if you are using data binding of course. If you aren’t using data binding, you can skip all of this and just follow the guide in the above link.
If you are still here …
I didn’t change anything in my CustomMap class in the shared project. All updates are in the iOS project. In here I have defined two classes: CustomMKAnnotationView and CustomMapRenderer. Let’s talk about CustomMKAnnotationView class first: it is the simpler.
The CustomMKAnnotationView class derives from MKAnnotationView. It adds a couple of new properties for the Id of the marker and a URL associated with the marker. Otherwise there is not a lot to be excited about. So lets move onto the CustomMapRenderer class.
The CustomMapRenderer class derives from MapRenderer. The first thing is that we have to override the OnElementChanged method. Just like Android, this either hooks up the native map to the cross platform map class in the shared project or unhooks it.
protected override OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e) { base.OnElementChanged(e); if (e.OldElement != null) { //... unhook events, native conrols etc } if (e.NewElement != null) { _customMap = (CustomMap) e.NewElement; _nativeMap = Control as MKMapView; _customPins = _customMap.CustomPins; _nativeMap.GetViewForAnnotation = GetViewForAnnotation; _nativeMap.CalloutAccessoryControlTapped += OnCalloutAccessoryControlTapped; _nativeMap.DidSelectAnnotationView += OnDidSelectAnnotationView; _nativeMap.DidDeselectAnnotationView += OnDidDeselectAnnotationView; } }
The most important things above are that you get a reference to our CustomMap object that was defined in the shared project; and also get a reference to the native map object (MKMapView).
Using the native map object from above, we can hook into events for it. We use these events to display the pins on the map and the info window when a user taps one of the pins.
Let’s take a look at the GetViewAnnotation method. This is the method that is used to show a custom marker on the map. In it we are passed in a reference to the marker. We use our GetCustomPin method to look up the information associated with the marker. In an effort to conserve memory, the map can reuse the view: and that is what is happening with the call to DequeueReusableAnnotation. If we can’t reuse, then we create a new one, specifying the image for the pin itself, and customizations for the callouts.
private MKAnnotationView GetViewForAnnotation( MKMapView mapView, IMKAnnotation annotation) { if (annotation is MKUserLocation) return null; MKAnnotationView ret = null; var pointAnnotation = annotation as MKPointAnnotation; var customPin = GetCustomPin(pointAnnotation); if (customPin == null) throw new Exception("My pin not found"); ret = mapView.DequeueReusableAnnotation(customPin.Id.ToString()); if (ret == null) { ret = new CustomMKAnnotationView( annotation, customPin.Id.ToString(), customPin.Url); ret.Image = UIImage.FromFile("custompin2.png"); ret.CalloutOffset = new CoreGraphics.CGPoint(0, 0); ret.LeftCalloutAccessoryView = new UIImageView(UIImage.FromFile("custompinimage.png")); ret.RightCalloutAccessoryView = UIButton.FromType(UIButtonType.DetailDisclosure); ((CustomMKAnnotationView) ret).Id = customPin.Id.ToString(); ((CustomMKAnnotationView) ret).Url = customPin.Url; } ret.CanShowCallout = true; return ret; }
Next we can take a quick look at the OnDidSelectAnnotationView. This is called when the user taps on the pin. You have the option of doing something custom … or just select the default that was setup in the GetAnnotationView function. In our case, we are going to see if the marker is associated with ID 1, and if it is, add in a custom image. Otherwise, we are just going to accept the default.
private void OnDidSelectAnnotationView( object sender, MKAnnotationViewEventArgs e) { var customView = e.View as CustomMKAnnotationView; _customPinView = new UIView(); if (customView.Id == "1") { _customPinView.Frame = new CoreGraphics.CGRect(0, 0, 200, 84); var image = new UIImageView(new CoreGraphics.CGRect(0, 0, 200, 84)); image.Image = UIImage.FromFile("custommapimage.png"); _customPinView.AddSubview(image); _customPinView.Center = new CoreGraphics.CGPoint(0, -(e.View.Frame.Height + 75)); e.View.AddSubview(_customPinView); } }
The OnDidDeselectAnnotationView method is called when the extended annotation is displayed and the user taps somewhere on the map, it will get rid of the extended information and free up the resources.
private void OnDidDeselectAnnotationView( object sender, MKAnnotationViewEventArgs e) { if (!e.View.Selected) { _customPinView.RemoveFromSuperview(); _customPinView.Dispose(); _customPinView = null; } }
Finally, let’s take a look at OnCalloutAccessoryControlTapped. After the user taps on the pin, extra data is displayed about the pin. If you tap on the extra data, this function is called. You can look at the information associated with the pin and act on it. In our case, we are going to grab the url and navigate to it.
private void OnCalloutAccessoryControlTapped( object sender, MKMapViewAccessoryTappedEventArgs e) { var customView = e.View as CustomMKAnnotationView; if (!String.IsNullOrWhiteSpace(customView.Url)) { UIApplication.SharedApplication.OpenUrl( new Foundation.NSUrl(customView.Url)); } }
And now just for a recap. If we want to make the custom map respond to our view model we have to listen for changes from the data binding system. This is almost exactly the same as the Android implementation where we override the OnElementPropertyChanged and listen for our property.
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (Element == null || Control == null) return; if (e.PropertyName == View.CustomMap.CustomPinsProperty.PropertyName) { UpdatePins(); } } private void UpdatePins() { if (_nativeMap == null) return; foreach (var p in _customMap.CustomPins) { MKPointAnnotation pa = new MKPointAnnotation { /// check git hub } _nativeMap.AddAnnotation(pa); } }
Don’t forget, the CustomPins is bound in our XAML page.
I find it pretty amazing that Xamarin Forms is able to share so much of the code. Really all we are doing in the separate projects is the presentation: all of the business logic is shared between all. Very cool.
Find all the code in my GitHub under the XamarinPrism repository. Find it under the MapRendererIos solution.