xamarin.iosuiswitch

Set both track and thumb colors for on and off state for UiSwitch in Xamarin.iOS


I want to have a switch with the colors reversed for On and Off state. Say in ON state, thumb color = blue and track color = red, then in OFF state I want to have thumb color = red and track color = blue.

How do I implement this in xamarin.iOS. (not forms). Thanks in advance.


Solution

  • You could try the following code:

    UISwitch uISwitch1 = new UISwitch();
    uISwitch1.Frame = new CoreGraphics.CGRect(100,100,30,50);
    uISwitch1.ThumbTintColor = UIColor.Red;
    uISwitch1.Layer.CornerRadius = (nfloat)(uISwitch1.Frame.Height / 2.0);
    uISwitch1.BackgroundColor = UIColor.Blue;
    uISwitch1.OnTintColor = UIColor.Red;
    
    //Detect switch value changed
    uISwitch1.ValueChanged += UISwitch1_ValueChanged;
    
    private void UISwitch1_ValueChanged(object sender, EventArgs e)
    {
        
        var s = sender as UISwitch;
        bool state = s.On;
        if (s.On)
        {
            s.ThumbTintColor = UIColor.Blue;
        }else
        {
            s.ThumbTintColor = UIColor.Red;
        } 
    }
    

    For more info, you could refer to UISwitch

    This is the result for on and off state:

    enter image description here

    enter image description here

    Hope it helps!