James Montemagno
James Montemagno

Live, Love, Bike, and Code.

Live, Love, Bike, and Code

Share


Tags


Adding a Disclosure Indicator Accessory to Xamarin.Forms ViewCells

Xamarin.Forms has a super powerful ListView. You can easily add custom cells, pull to refresh, headers, footers, and even sections with just a few lines of code. A while ago I talked about how to easily group items to display section headers in the ListView. You get a great native styling of section headers with just a few simple lines of code. One thing I have noticed and has bothered me specifically with iOS is the lack of the Disclosure Indicator on cells. A Disclosure Indicator you say? What is that you may be asking? A Disclosure Indicator is a special Accessory on a Cell that has an arrow pointing to the right, normally indicating you can navigate another level deep. It looks like this:

This is just one of the 3 types of Accessories that you can have on a UITableViewCell. You can read all about them on the Xamarin documentation recipe and when you should use each of them. 

So what’s the issue?

The reason I am writing this blog is because out of the box Android and Windows have no concept of Accessories on cells. Users of these platforms simply expect that when you tap on an item you navigate, but on iOS you should really have the Disclosure Indicator or other accessory. Since there is no way to actually abstract this Xamarin.Forms simply leaves out the accessories of ListView cells, which is sad, but makes complete sense.

We can fix it! 

Xamarin.Forms has the concept of custom renderers that can be used to customize controls, add custom controls, and even completely replace how a control is rendered! This is crazy and amazing as we can use a custom renderer to replace the default ViewCell implementation with our own that adds in the accessories. Instead of creating our own custom cell we will simply tell Xamarin.Forms to use our ViewCellRenderer for iOS. We can then leverage the fact that the “StyleId” property doesn’t do much besides providing the ability to do awesome things with Xamarin.UITest and Test Cloud. We can use the StyleId property to set what type of indicator we want. In your iOS project simply add a new class called ViewCellRenderer and copy in this code:

Now, all of your ViewCells will automatically be updated with an indicator by default or you can set the StyleId to anything you want in XAML or C#. 

Since I am am creating this renderer explicitly for a “ViewCell” with a “ViewCellRenderer” this means that only my custom ViewCell’s will have this new fancy indicator, but you could apply this same exact concept to TextCell with a TextCellRender or a ImageCell and ImageCellRenderer. It is amazing and really easy to implement without creating custom Xamarin.Forms controls. Enjoy and happy ViewCell Accessorizing!

Copyright © James Montemagno 2015 All rights reserved. Privacy Policy

View Comments