Search code examples
xamarin.formscustom-renderer

iOS 14 DatePicker renderer


I am having some difficulty figuring out how to properly update my existing custom renderer I have for my DatePicker on iOS to display the DatePicker with a different preferred style as is mentioned in this article here (albeit it is for swift) https://medium.com/better-programming/introducing-swifts-new-modern-date-picker-37bb5e0a106

My renderer is as follows:

public class BorderlessDatePickerRenderer : DatePickerRenderer
    {
        
        public override void LayoutSubviews()
        {
            base.LayoutSubviews();
            
            
            var element = Element as BorderlessDatePicker;
            Control.BorderStyle = UITextBorderStyle.None;
            if (element.Date.Year == 1900) {
                    Control.Text = "";
            }
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            var element = Element as BorderlessDatePicker;

            if (Control != null && element.Date.Year == 1900) {
                    Control.Text = "";
            }
        }

The BorderlessDatePicker itself is just an empty class that extends the DatePicker Xamarin.Forms control. The root of my woes is that I am not sure how to properly set a PreferredDatePickerStyle on my Control object given that Control is a UITextField under the hood instead of a UIDatePicker. In essence what I would like to do is instead of displaying the Date picker using the compact style that seems to be default for iOS 14, I would like for it to be displayed as wheels instead by being to do something like:

PreferredDatePickerStyle = UIDatePickerStyle.Wheels;


Solution

  • After some more researching, and browsing the xamarin github, I've come across this solution:

    protected override void OnElementChanged(ElementChangedEventArgs<DatePicker> e)
        {
            base.OnElementChanged(e);
    
            if(e.NewElement != null && this.Control != null)
            {
                try
                {
                    if (UIDevice.CurrentDevice.CheckSystemVersion(14, 0))
                    {
                        UIDatePicker picker = (UIDatePicker)Control.InputView;
                        picker.PreferredDatePickerStyle = UIDatePickerStyle.Wheels;
                    }
    
                } catch (Exception ex)
                {
                    Log.Error(ex, "Failed to set PreferredDatePickerStyle to be UIDatePickerStyle.Wheels for iOS 14.0+");
                }
            }
        }