Xamarin.Forms: Custom Context Actions on iOS

Xamarin.Forms: Custom Context Actions on iOS


Hello folks now is time to talk about customize context action views on Xamarin.Forms cell for iOS (yes the red/light-gray options that appear when you swipe a cell) the default colors are not a good-looking, so right now is a little bit tricky to achieve that but we will use a reflection technique to achieve the next two escenarios:
  • Change background color for default and destructive context action
  • Set custom view for default and destructive context action
first at all, lets take a look to native impl. on Xamarin.Forms Github project on the next url



Here we have two key items "DestructiveBackground" and "NormalBackground" both are the Images  that Xamarin.Forms use to put as background on the default ContextActions view(Gray/Red)


Not bad but sometimes we need to put some love into the design. at this point we found a major issue both ContextActionsCell & Destructive/Normal background properties are internal/private which basically means that we are not able to modify directly due protection level here is when Reflection is coming to help us to handle it.

Lets analyze how we can achieve this the steps are listed next
  1. Get assembly info for Xamarin.Forms.Platform.iOS(the one that contains ContextActionsCell class).
  2. Get Type info for internal ContextActionsCell class.
  3. Get Field infor for DestructiveBackground & NormalBackground properties
  4. Set or Get value for static DestructiveBackground / NormalBackground properties
Sound a little bit hard but let's see code this will be easy I promise you.


Told you with that 4 lines of code now you're able to modify that internal properties based on that now we need to create a dependency service interface to expose a simple way to change both properties and also we will need to create an iOS specific implementation.

After complete the iOS implementation now we're able to retrieve the native manager and apply whether custom background color and/or the custom view using follow code:

Also theres an small trick if you want to use a custom VIEW you'll need to add some hack spaces into the Text definition of the MenuItem as is displayed in the next fragment of code:

After use the previous code you'll get the next result



IMPORTANT NOTE:
As you noticed this implementation is very customized which means that may change between Xamarin.Forms versions the version used on this example is the latest version 3.0.0.550146
So I highly recommend to be careful if you implement this way every time that you want to upgrade or downgrade the Xamarin.Forms version in your project

GITHUB REPOSITORY:

if you want to look a complete demo you can download it from here:

HAPPY CODE!!!!


Comentarios

Entradas populares de este blog

Bluetooth Arduino + Xamarin.Android

C# Interface Ejemplo Sencillo

Simple ListView with Xamarin.Forms