'Xamarin.iOS can I have one class that some buttons can inherit from so they get the same looks?

I'm very new to Xamarin and I am currently working on a Xamarin.iOS project where I have added buttons in Xcode. How would I go about it if I want to style some of the buttons the same way without having to repeat myself in the code? Can I create a class or something that the specific buttons can inherit from?



Solution 1:[1]

How would I go about it if I want to style some of the buttons the same way without having to repeat myself in the code? Can I create a class or something that the specific buttons can inherit from?

Answer:This could be achieved through Custom Renderer.

First,in your shared project,create a base class:

CustomButton.cs


    public class CustomButton : Button
   {
   }

Then,in your iOS project,create a Custom Renderer:

[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace App26.iOS
{


   public class CustomButtonRenderer : ButtonRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            // Cleanup
        }

        if (Control != null)
        {
            //set custom style here
            Control.TitleShadowOffset = new CoreGraphics.CGSize(1, 1);
            Control.SetTitleShadowColor(Color.Black.ToUIColor(), UIKit.UIControlState.Normal);
            Control.BackgroundColor = UIColor.Green;
            Control.Title(UIControlState.Selected);

         }
       }
    }
}

Last but not least, consume your custom button like below:

<local:CustomButton/>

MS official docs link: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1