Define background color on UIButton depending on state

In Xamarin.iOS - Is it possible to define the background color of an UIButton depending on the different states? Just as the SetTitleColor:

button.SetTitleColor(UIColor.White, UIControlState.Normal);
button.SetTitleColor(UIColor.Black, UIControlState.Disabled);

Best Answer

Answers

  • CasperNybroeCasperNybroe USMember

    Thanks Gavin
    It worked perfectly.

  • Chris.3704Chris.3704 USUniversity ✭✭

    Another option if you don't want to sub-class UIButton is to create a Platform Effect in which you check if the Xamarin.Forms IsEnabled flag and set the Background accordingly.

                    Xamarin.Forms.Button element = Element as Xamarin.Forms.Button;
                    UIKit.UIButton control = Control as UIKit.UIButton;
    
                    // Set Button background color
                    if (element.IsEnabled)
                    {
                        control.BackgroundColor = enabledColor;
                    }
                    else
                    {
                        control.BackgroundColor = disabledColor;
                    }
    
  • JoeTomkinsonJoeTomkinson GBMember ✭✭

    @GavinGrant said:
    Yes. Try this Subclass UIButton.

    [Register("Button")] public class Button : UIButton { protected void SetBackgroundColorForState(UIControlState state) { switch (state) { case UIControlState.Normal: { BackgroundColor = <Your desire colour> break; } case UIControlState.Highlighted: { BackgroundColor = <Your desire colour> break; } case UIControlState.Disabled: { BackgroundColor = <Your desire colour> break; } } } public override bool Enabled { get { return base.Enabled; } set { base.Enabled = value; var state = value ? UIControlState.Normal : UIControlState.Disabled; SetBackgroundColorForState(state); } } public override bool Highlighted { get { return base.Highlighted; } set { base.Highlighted = value; var state = value ? UIControlState.Highlighted : UIControlState.Normal; SetBackgroundColorForState(state); } } }

    Excellent answer, exactly what I was looking for, such a simple way of adjusting the effects of different selection types. I'm already using this to create global appearances across certain controls, so adding to that is just gravy.

Sign In or Register to comment.