2
votes

How to change the color of the switch button when toggling for IOS Xamarin Forms? Custom render will set the color just once:

Xamarin forms toggle button default color on IOS

and it won't be changed when the Switch is toggled. Same goes and for setting values in AppDelegate.cs it will be done only once. I need this:

enter image description hereenter image description here

In IOS its only possible using:

UISwitch.Appearance.ThumbTintColor = UIColor.Brown;
UISwitch.Appearance.OnTintColor = UIColor.Red;

but how I can access that field if my switch is in PCL project, and its used for Xamarin Forms.

2

2 Answers

3
votes

I solved this with:

public class CustomSwitchRenderer: SwitchRenderer
{       
    protected override void OnElementChanged(ElementChangedEventArgs<Switch> e)
    {
        Element.Toggled += ElementToggled;

        base.OnElementChanged(e);

        if (Control != null)
        {                
            UpdateUiSwitchColor();
        }
    }

    private void ElementToggled(object sender, ToggledEventArgs e)
    {
        UpdateUiSwitchColor();
    }

    private void UpdateUiSwitchColor()
    {
        var temp = Element as Switch;

        if (temp.IsToggled)
        {
            Control.ThumbTintColor = Color.FromHex(ColorConstants.BlueHex).ToUIColor();
            Control.OnTintColor = Color.FromHex(ColorConstants.OblueLightHex).ToUIColor();
        }
        else
        {
            Control.ThumbTintColor =  Color.FromHex(ColorConstants.GrayHex).ToUIColor();
        }
    }
}

So, I activated event whenever Toggle is executed:

Element.Toggled += ElementToggled;
1
votes

You can still do it in a custom renderer. Just listen to the switch's ValueChanged event, there you can check if it is on or off, and update the color.

For example, in your iOS project's custom switch renderer class:

protected override void OnElementChanged(ElementChangedEventArgs<Switch> e)
{
    base.OnElementChanged(e);

    Control.ValueChanged += Control_ValueChanged;
}

private void Control_ValueChanged(object sender, EventArgs e)
{
    if (Control.On)
    {
        // set on colors
    }
    else
    {
        // set off colors
    }
}