How to make a UIDatePicker label invisible still interactive in Xamarin.ios?

Issue

I need to open a UIDatePicker programatically in my Xamarin.ios project. Unfortunately it is not allowed and there is no public api. But I got some tricks which are native code from Open UIDatePicker programmatically in iOS 14 I am trying to implement this trick: https://stackoverflow.com/a/65430977/13026962 I managed to add a UIDatePicker on top of my label. This is my code:

            lblFromDate.UserInteractionEnabled  false;
            var datePicker  new UIDatePicker(new CGRect(x: lblFromDate.Frame.X, y: 
            lblFromDate.Frame.Y, width: lblFromDate.Frame.Width, height: lblFromDate.Frame.Height));
            datePicker.Mode  UIDatePickerMode.Date;
            datePicker.ValueChanged + DatePicker_ValueChanged;
            Add(datePicker);

enter image description here

But I want to hide the date picker somehow but still need that to be interactive so that when tapping on the label (actually tapped the date picker), the date picker animates out.

The second problem is I want to close the calendar modal when any date is tapped. But I found only value changed event. Is it possible to close the calendar modal programmatically, would be a great help for me. Here is the calendar modal that pops up after tapping on the date picker:

enter image description here

Solution

To your first problem: You can set the datepicker’s PerferredDatePickerStyle as compact, and set the color of label which on the datepicker as white to cover the datepicker. Also set label’s enabled as false. code like:

mydatapicker.PerferredDatePickerStyleUIDatePickerStyle.Compact;
mylabel.BackgroundColorUIColor.White;
//.....  

To change it Text, add follow code:

mydatapicker.valuechanged+Datepicker_Valuechanged;
private void Datepicker_Valuechanged(object sender,EventArgs e) 
{mylabel.Textmydatapicker.Date.ToString();}

To your second problem I am afraid there is no appropriate way to close the calendar modal when any date is tapped.

Hope these could be helpful to you.

1.In storyboard,set label’s enabled as false. enter image description here

2.before click

enter image description here

3.click

enter image description here

4.after value changed

enter image description here

5.code behind

enter image description here

Answered By – Adrain Zhu -MSFT

Leave a Comment