iOS设备上Xamarin.Forms TimePicker设置英文AM/PM的方法
Xamarin.Forms TimePicker iOS真机不显示AM/PM标识的解决办法
在Xamarin.Forms中使用TimePicker并设置Format="h:mm tt"时,iOS真机设备无法显示英文的AM/PM标识,但iOS模拟器一切正常,尝试自定义渲染器后问题仍未解决。
代码示例
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="TTTTT.MainPage"> <StackLayout> <Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0"> <Label Text="Welcome to Xamarin.Forms!" HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/> </Frame> <Label Text="Start developing now" FontSize="Title" Padding="30,10,30,10"/> <Label Text="Make changes to your XAML file and save to see your UI update in the running app with XAML Hot Reload. Give it a try!" FontSize="16" Padding="30,0,30,0"/> <Label FontSize="16" Padding="30,24,30,0"> <Label.FormattedText> <FormattedString> <FormattedString.Spans> <Span Text="Learn more at "/> <Span Text="https://aka.ms/xamarin-quickstart" FontAttributes="Bold"/> </FormattedString.Spans> </FormattedString> </Label.FormattedText> </Label> <TimePicker Format="h:mm tt"></TimePicker> </StackLayout> </ContentPage>
解决方法
1. 检查iOS真机区域设置
iOS真机的系统区域会影响时间格式显示。如果设备地区不是英文地区,系统会自动用当地的上午/下午标识,而非英文AM/PM。
- 打开设备「设置」→「通用」→「语言与地区」
- 将「地区」改为美国或其他英文地区,再测试TimePicker显示效果。
2. 用自定义渲染器强制设置英文格式
如果不想修改系统设置,可通过iOS自定义渲染器强制TimePicker使用英文文化解析格式:
using Foundation; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(TimePicker), typeof(CustomTimePickerRenderer))] namespace YourAppNamespace.iOS.Renderers { public class CustomTimePickerRenderer : TimePickerRenderer { protected override void OnElementChanged(ElementChangedEventArgs<TimePicker> e) { base.OnElementChanged(e); if (Control != null) { var formatter = new NSDateFormatter(); formatter.Locale = NSLocale.FromLocaleIdentifier("en_US_POSIX"); formatter.DateFormat = "h:mm a"; // iOS用a表示AM/PM,对应Xamarin.Forms的tt Control.DatePicker.Locale = formatter.Locale; Control.DatePicker.DateFormat = formatter.DateFormat; } } } }
替换YourAppNamespace为你的项目命名空间即可。
3. 全局设置应用文化为英文
在App.xaml.cs的OnStart方法中,全局设置应用使用英文文化:
using System.Globalization; using System.Threading; protected override void OnStart() { var enCulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = enCulture; Thread.CurrentThread.CurrentUICulture = enCulture; }
这种方式会让整个应用的日期、时间格式都遵循英文地区规则,适合需要全局英文格式的场景。
内容的提问来源于stack exchange,提问作者Yalamandarao
相关产品推荐
相关产品推荐

