Search code examples
xamarin.formsxamarin.ioscustom-renderer

Xamarin custom renderer rounded corners results in 2 borders


I created rounded corners on iOS using a custom renderer:

protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.DatePicker> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            Control.TextAlignment = UIKit.UITextAlignment.Center;
            Control.BackgroundColor = Color.FromHex(Consts.PICKER_BACKGROUND_COLOR).ToUIColor();
            Control.TextColor = Color.FromHex(Consts.PICKER_TEXT_COLOR).ToUIColor();
            Control.Layer.CornerRadius = Consts.PICKER_CORNER_RADIUS;
            Control.Layer.BorderWidth = Consts.PICKER_STROKE_WIDTH;
            Control.Layer.BorderColor = Color.FromHex(Consts.PICKER_STROKE_COLOR).ToCGColor();

        }
    }

This is working; and gives me to following result:

Rounded corners

However, if you look carefully, there are 2 borders arround the date and time picker. One border i added, and a 'default' border.

This is only happening for DatePicker, TimePicker and Picker. Not for Editor or Entry.

Questions: Why are there 2 borders? And how can i remove the 'default' border?


Solution

  • Try to add the following code to your method:

    if (Control != null)
      {
        Control.TextAlignment = UIKit.UITextAlignment.Center;
        Control.BackgroundColor = Color.FromHex(Consts.PICKER_BACKGROUND_COLOR).ToUIColor();
        Control.TextColor = Color.FromHex(Consts.PICKER_TEXT_COLOR).ToUIColor();
        Control.Layer.MasksToBounds=true; //It is important
            ... 
      }
    

    Control.Layer.MasksToBounds=true;

    means if the sublayer cuts the layer boundary, the default is false, and setting it to true will cut out the excess.

    I used the above code and it works fine.