如何根据Xamarin

问题描述

我将Xamarin.Forms更新为最新版本4.8.0.1560。我设法在Android和iOS上都绑定了时间选择器。与我的应用程序唯一的区别是,当用户在手机中使用24时间设置时,时间选择器“卡住”了12小时格式。

为此,我在iOS中创建了一个自定义渲染器

[assembly: ExportRenderer(typeof(TimePicker),typeof(TimeRenderer))]
namespace TabsApp.iOS.custom.renderers
{
    public class TimeRenderer : TimePickerRenderer
    {

        protected override void OnElementChanged(ElementChangedEventArgs<TimePicker> e)
        {
            base.OnElementChanged(e);
            int hours = Element.Time.Hours;
            int minutes = Element.Time.Minutes;

            if (!Is12Hours())
            {
                var timePicker = (UIDatePicker)Control.InputView;  
                timePicker.Locale = new NSLocale("no_nb");  
            }
            
            string format = Is12Hours()?"hh:mm tt":"HH:mm";
            DateTime currTime = DateTime.Now;
            currTime = new DateTime(currTime.Year,currTime.Month,currTime.Day,hours,minutes,0);
            Control.Text = currTime.ToString(format);
          
        }
        
        
        
        private bool Is12Hours()
        {
            var dateFormatter = new NSDateFormatter();
            dateFormatter.DateStyle = NSDateFormatterStyle.None;
            dateFormatter.TimeStyle = NSDateFormatterStyle.Short;

            var dateString = dateFormatter.ToString(NSDate.Now);
            var isTwelveHourFormat = 
                dateString.Contains(dateFormatter.AMSymbol) || 
                dateString.Contains(dateFormatter.PMSymbol);
            return isTwelveHourFormat;
        }
    }
}
加载应用程序后,将调用

OnElementChanged,它将显示正确的时间格式。更改时间时,不会调用此回调。我需要覆盖其他功能吗?

sample

解决方法

最后,我从xamarin形式中找到了答案。您将需要更改/添加自定义时间选择器渲染器。

这是代码

[assembly: ExportRenderer(typeof(TimePicker),typeof(TimeRenderer))]
namespace TabsApp.iOS.custom.renderers
{
    public class TimeRenderer : TimePickerRenderer
    {
       
        protected override void OnElementChanged(ElementChangedEventArgs<TimePicker> e)
        {
            base.OnElementChanged(e);

            if (Is12Hours())
            {
                Element.Format = "hh:mm tt";
            }
            else
            {
                var timePicker = (UIDatePicker)Control.InputView;  
                timePicker.Locale = new NSLocale("no_nb");

                Element.Format = "HH:mm";
            }
          
        }


        private bool Is12Hours()
        {
            var dateFormatter = new NSDateFormatter();
            dateFormatter.DateStyle = NSDateFormatterStyle.None;
            dateFormatter.TimeStyle = NSDateFormatterStyle.Short;

            var dateString = dateFormatter.ToString(NSDate.Now);
            var isTwelveHourFormat = 
                dateString.Contains(dateFormatter.AMSymbol) || 
                dateString.Contains(dateFormatter.PMSymbol);
            return isTwelveHourFormat;
        }
    }
}