1
votes

I'm trying to write a CustomRenderer for iOS through which I want to change the BackgroundColor of the button when the user touches it. So far i got this:

public class BtnRendereriOS : ButtonRenderer
{

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


        if (Control != null)
        {
            Control.BackgroundColor = UIColor.FromRGB(3, 169, 244);
            Control.Layer.CornerRadius = 0;

        }
        Control.TouchUpInside += (sender, UIButton) => {
            Control.BackgroundColor = UIColor.Brown;
        };


    }
}

Its not working however. I guess there needs to be some sort of eventhandler in order to make this possible.

1

1 Answers

1
votes

The background colors needs to be initially set (if not the default color), then you need to set it back to that same color on TouchUpInside and TouchUpOutside. On TouchDown, set it to the color that you wish it to be while the button is being pressed.

Toggle background color:

if (Control != null)
{
    void BackgroundNormalState(object sender)
    {
        (sender as UIButton).BackgroundColor = UIColor.Green;
    }
    BackgroundNormalState(Control);
    Control.TouchUpInside += (object sender, EventArgs e) =>
    {
        BackgroundNormalState(sender);
    };
    Control.TouchUpOutside += (object sender, EventArgs e) =>
    {
        BackgroundNormalState(sender);
    };
    Control.TouchDown += (object sender, EventArgs e) =>
    {
        (sender as UIButton).BackgroundColor = UIColor.Red;
    };
}

Update:

Can i change my textcolor through this methodgroup as well?

There are is a SetTitleColor where you can assign different colors to the different UIControlState values, Normal and Highlighted are the ones to start with:

Control.SetTitleColor(UIColor.Red, UIControlState.Normal);
Control.SetTitleColor(UIColor.Green, UIControlState.Highlighted);