Alan2
Alan2

Reputation: 24572

How can I use a custom renderer to set the color of a switch by default?

I currently have this custom renderer to set the color of a switch in response to parameters.

class ExtSwitchRenderer : SwitchRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Switch> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null || e.NewElement == null) return;

        ExtSwitch s = Element as ExtSwitch;

        this.Control.OnTintColor = s.SwitchOnColor.ToUIColor();

    }
}

I would like to modify this so I don't need to specify a parameter such as OnColor="Red". So there would be no OnElementChanged event

Can someone suggest to me how I can do set the OnColor to red with code in the renderer rather than on the parameter line of my XML in iOS?

Is there some other event that I can override?

Upvotes: 0

Views: 507

Answers (1)

Bruno Caceiro
Bruno Caceiro

Reputation: 7189

IF you upgrade the Xamarin Forms version in your project ( to 3.1) that is a Bindable Property now:

 <Switch OnColor="Red" />

You can also modify your renderer, and set the color, regardless of the binding:

 Control.OnTintColor = UIColor.FromRGB (204, 153, 255);

Or, in AppDelegate, apply to all Switches:

public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{

  // switch
    UISwitch.Appearance.OnTintColor = UIColor.FromRGB(0x91, 0xCA, 0x47); // green
    // required Xamarin.Forms code
    Forms.Init ();
    LoadApplication (new App ());
    return base.FinishedLaunching (app, options);
}

Upvotes: 1

Related Questions